Clean and fast (29ms) C++ solution


  • 0
    P
    class Solution {
        int getInt(string &s, int &pos) {
            // pos will change to the first char after this integer
            int sign = s[pos] == '-' ? -1 : 1;
            if (sign == -1) pos++;
            int res = 0;
            while (isdigit(s[pos])) {
                res *= 10;
                res += (s[pos] - '0');
                pos++;
            }
            return sign == -1 ? -res : res;
        }
    
    public:
        NestedInteger deserialize(string s) {
            int i = 0;
            vector<NestedInteger> stk;
            stk.push_back(NestedInteger());
            while (i < s.size()) {
                switch (s[i]) {
                    case ',':
                        i++;
                        break;
    
                    case '[':
                        stk.push_back(NestedInteger());
                        i++;
                        break;
    
                    case ']':
                        stk[stk.size()-2].add(stk.back());
                        stk.pop_back();
                        i++;
                        break;
    
                    default:
                        stk.back().add(NestedInteger(getInt(s, i)));
                        break;
                }
            }
    
            return stk.back().getList()[0];
        }
    };
    

Log in to reply
 

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