My simple short Iterative java solution


  • 0
    Y

    Use a int start to record the start position of the integer to be parsed.
    Note that case ']' and case ',' can be merged as one.

    class Solution {
        public NestedInteger deserialize(String s) {
            if(s.length() == 0) return new NestedInteger();
            Stack<NestedInteger> stack = new Stack<>();
            char[] c = s.toCharArray();
            if(c[0] != '[') return new NestedInteger(Integer.parseInt(s));
            int start = 0;
            for(int i = 0; i < c.length; i ++) {
                if(c[i] == '[') {
                    stack.push(new NestedInteger());
                    start = i + 1;
                }
                else if(c[i] == ']' || c[i] == ',') {
                    String temp = s.substring(start, i);
                    if(c[i - 1] != ']') {
                        if(!temp.isEmpty()) 
                            stack.peek().add(new NestedInteger(Integer.parseInt(temp)));
                    }
                    else {
                        NestedInteger n1 = stack.pop();
                        stack.peek().add(n1);
                    }
                    start = i + 1;
                }
            }
            return stack.pop();
        }
    }
    

Log in to reply
 

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