Concise easy understanding C++ solution with comments


  • 0
    H

    Because the input string is well-formed, it is easy to determine if the string is an integer or list by checking if the first character is '[' or not. If it is list, the elements must be separated by ',' with well-formed nested objects, i.e. '[' and ']' in the nested objects are well paired.

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            NestedInteger res;
            if (s[0] == '[') {
                s[s.size()-1] = ',';
                int i = 0;
                int count = 0;
                string sub;
                while(++i < s.size()) {
                    if (s[i] == ',' && count == 0 && sub.size()) {
                        res.add(deserialize(sub));
                        sub.clear();
                    } else {
                        if (s[i] == '[') count++;
                        if (s[i] == ']') count--;
                        sub.push_back(s[i]);
                    }
                }
            } else {
                res.setInteger(stoi(s));
            }
            return res;
        }
    };
    

Log in to reply
 

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