A Java Recursive Solution


  • 0
    O
        public NestedInteger deserialize(String s) {
            if (s.charAt(0) != '[')
                return new NestedInteger(Integer.valueOf(s));
            
            NestedInteger res = new NestedInteger();
            for (int i = 1, sgn = 1, num = 0; i < s.length() - 1; i++) {
                char ch = s.charAt(i);
                if (Character.isDigit(ch)) {
                    num = num * 10 + (int)(ch - '0');
                    if (!Character.isDigit(s.charAt(i + 1))) {
                        res.add(new NestedInteger(sgn * num));
                        num = 0;
                        sgn = 1;
                    }
                } else
                if (ch == '-')
                    sgn = -1;
                else
                if (ch == '[') {
                    int tail = i + 1;
                    for (int cnt = 1; cnt > 0; tail++)
                        if (s.charAt(tail) == '[') cnt++;
                        else
                        if (s.charAt(tail) == ']') cnt--;
                    res.add(deserialize(s.substring(i, tail + 1)));
                    i = tail;
                }
            }
            return res;
        }
    

Log in to reply
 

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