C++ Non-recursive solution


  • 0
    A

    The given interface add(const NestedInteger &ni) is actually implemented as object copy which is unexpected to me.

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            if (s[0] != '[') return NestedInteger(stoi(s));
            NestedInteger head, *n = &head;
            stack<NestedInteger*> k;
            for (uint i = 1, ii = s.size(); i < ii; i++) {
                if (s[i] == '[') {
                    NestedInteger tmp;
                    n->add(tmp);
                    k.push(n);
                    n = &n->getList().back();
                } else if (s[i] == ']') {
                    if (!k.empty()) {
                        n = k.top();
                        k.pop();
                    }
                } else if (s[i] != ',') {
                    size_t pos;
                    NestedInteger tmp(stoi(s.substr(i), &pos));
                    n->add(tmp);
                    i += pos - 1;
                }
            }
            return head;
        }
    };
    

Log in to reply
 

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