leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0385.cpp (1936B)


      1 /**
      2  * // This is the interface that allows for creating nested lists.
      3  * // You should not implement it, or speculate about its implementation
      4  * class NestedInteger {
      5  *   public:
      6  *     // Constructor initializes an empty nested list.
      7  *     NestedInteger();
      8  *
      9  *     // Constructor initializes a single integer.
     10  *     NestedInteger(int value);
     11  *
     12  *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
     13  *     bool isInteger() const;
     14  *
     15  *     // Return the single integer that this NestedInteger holds, if it holds a single integer
     16  *     // The result is undefined if this NestedInteger holds a nested list
     17  *     int getInteger() const;
     18  *
     19  *     // Set this NestedInteger to hold a single integer.
     20  *     void setInteger(int value);
     21  *
     22  *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
     23  *     void add(const NestedInteger &ni);
     24  *
     25  *     // Return the nested list that this NestedInteger holds, if it holds a nested list
     26  *     // The result is undefined if this NestedInteger holds a single integer
     27  *     const vector<NestedInteger> &getList() const;
     28  * };
     29  */
     30 class Solution {
     31   public:
     32     NestedInteger deserialize(const string &s) const {
     33         if (s[0] != '[') return NestedInteger(stoi(s));
     34 
     35         stack<NestedInteger> st;
     36         const int n = size(s);
     37 
     38         for (int i = 0; i < n - 1; i++) {
     39             if (s[i] == ',') continue;
     40 
     41             if (s[i] == '[')
     42                 st.push({});
     43             else if (s[i] == ']') {
     44                 const auto top = st.top();
     45                 st.pop();
     46                 st.top().add(top);
     47             } else {
     48                 const int start = i;
     49                 while (i < n && s[i] != '[' && s[i] != ']' && s[i] != ',')
     50                     i++;
     51                 st.top().add(stoi(s.substr(start, i - start)));
     52                 i--;
     53             }
     54         }
     55 
     56         return st.top();
     57     }
     58 };