Java iterative solution


  • 0
    public class Solution {
        public NestedInteger deserialize(String s) {
            Stack<NestedInteger> stack = new Stack<NestedInteger>();
            int sign = 1;
            int index = 0;
            Integer intValue = null;
            NestedInteger result = null;
            while(index < s.length()) {
                char ch = s.charAt(index);
                if(ch == '[') {
                    NestedInteger ni = new NestedInteger();
                    if(result == null) {
                        result = ni;
                    }
                    if(!stack.empty()) {
                        stack.peek().add(ni);
                    }
                    stack.push(ni);
                } else if(ch == ']' || ch == ',') {
                    if(intValue != null) {
                        stack.peek().add(new NestedInteger(intValue));
                        intValue = null;
                        sign = 1;
                    }
                    if(ch == ']') {
                        stack.pop();
                    }
                } else if(ch == '-') {
                    sign = -1;
                } else {
                    intValue = (intValue == null ? 0 : intValue) * 10 + sign * (ch - '0');
                }
                index++;
            }
            return result != null ? result : new NestedInteger(intValue);
        }
    }
    

Log in to reply
 

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