C++ solution read char one by one and using stack


  • 0
    A
    class Solution {
    public:
        NestedInteger deserialize(string s) {
            stack<NestedInteger> stk;
            NestedInteger ans;
            int val = 0, sign = 1;
            bool inNum = false;
            for (char c : s) {
                if (isdigit(c)) {
                    val = val * 10 + c - '0';
                    inNum = true;
                }
                else if (c == '-')
                    sign = -1;
                else if (c == '[')
                    stk.push(NestedInteger());
                else if (c == ']') {
                    if (inNum) {
                        stk.top().add(NestedInteger(val * sign));
                        val = 0;
                        inNum = false;
                        sign = 1;
                    }
                    
                    NestedInteger t = stk.top();
                    stk.pop();
                    if (stk.empty())
                        ans = t;
                    else
                        stk.top().add(t);
                }
                else { // ','
                    if (inNum) {
                        stk.top().add(NestedInteger(val * sign));
                        val = 0;
                        inNum = false;
                        sign = 1;
                    }
                }
            }
            
            if (inNum)
                ans = NestedInteger(val * sign);
            return ans;
        }
    };
    

Log in to reply
 

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