Recursive C++ solution


  • 0
    S

    Special case handling of the "1" case.

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            int e=0;
            if (s.find_first_of('[',0) == string::npos) return NestedInteger(stoi(s));
            return construct(1, s, e);
        }
        
        NestedInteger construct(int s, string &n_s, int &e) {
            NestedInteger n;
            int i=s;
            
            while (i < n_s.size()) {
                char c = n_s[i];
                if (c == ']') {
                    e=i; return n;
                } if (c == '[') {
                    n.add(construct(i+1, n_s, e));
                    i = e+1;
                } else if (c == ',') {
                    ++i;
                } else {
                    string t;
                    while (i < n_s.size() && ((n_s[i] >= '0' && n_s[i] <= '9') || (n_s[i] == '-'))) {
                        t.push_back(n_s[i++]);
                    }                
                    
                    int x = stoi(t);
                    n.add(x);
                }
            }
            
            e=i;
            return n;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.