C++ Recursion


  • 0

    Um, It takes me quit a long time to figure out the parsing rules.

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            if (s.empty())
                return NestedInteger();
            if (s[0] != '[') {
                return NestedInteger(stoi(s));
            }
            int n = s.size(), i = 1;
            NestedInteger num;
            while (i < n - 1) {
                if (s[i] == '[') {
                    int cnt = 1, j = i + 1;
                    while (cnt) {
                        if (s[j] == '[')
                            cnt++;
                        else if (s[j] == ']')
                            cnt--;
                        j++;
                    }
                    num.add(deserialize(s.substr(i, j - i)));
                    i = j;
                } else if (s[i] == ',') {
                    i++;
                    continue;
                }
                else {
                    int j = i + 1;
                    while (j < n - 1 && s[j] != ',')
                        j++;
                    num.add(deserialize(s.substr(i, j - i)));
                    i = j;
                }
            }
            return num;
        }
    };
    

Log in to reply
 

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