Very short recursive solution


  • 3
    Q
    class Solution {
    public:   
        NestedInteger parse(string& s, int& i) {
          if(s[i]=='[') {
              ++i;
              NestedInteger list;
              while(s[i] != ']') {
                  list.add(parse(s,i));
                  if(s[i] ==',') ++i;
              }
              ++i;
              return list;
          } else {                       
            int sum = 0;
            int sign=1;
            if(s[i] == '-'){ sign = -1; ++i;}
            while(isdigit(s[i])) { sum *= 10; sum+= s[i]-'0'; ++i;}
              return NestedInteger(sum*sign);
          }
        }
        NestedInteger deserialize(string s) {
            int i = 0;
            return parse(s, i);
        }
    };

Log in to reply
 

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