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)


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