C++ clean recursive code


  • 0
    C
    NestedInteger parse(string& s, int& i) {
        if(s[i] == '[') {
            i++;
            NestedInteger lst;
            while(s[i] != ']') {
                lst.add(parse(s, i));
                if(s[i] == ',') i++;
            }
            i++;
            return lst;
        } else {
    	if(s[i] == '-' || isdigit(s[i])) {
                int num = 0, sign = 1;
                if(s[i] == '-') {sign = -1; i++;}
                while(isdigit(s[i])) num = num * 10 + s[i++] - '0';
                return NestedInteger(sign * num);
            }
            return NestedInteger();
        }
    }
    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.