19ms JAVA Solution With Stack


  • 0
    Y
    
    public class Solution {
        public NestedInteger deserialize(String s) {
            int left = 0;
            int num = 0;
            boolean minus = false;
            Deque<NestedInteger> stack1 = new ArrayDeque<NestedInteger>();
            while(left < s.length()){
                char c = s.charAt(left);
                if(c == '['){
                    stack1.push(new NestedInteger());
                }else if(c == ']'){
                    NestedInteger tmp = new NestedInteger();
                    if(s.charAt(left - 1) == ']' || s.charAt(left - 1) == '[')
                        tmp = stack1.pop();
                    else{
                        if(minus)
                            num *= -1;
                        tmp = stack1.pop();
                        tmp.add(new NestedInteger(num));
                    }
                    if(!stack1.isEmpty()){
                        NestedInteger list = stack1.pop();
                        list.add(tmp);
                        stack1.push(list);
                    }
                    else
                        stack1.push(tmp);
                    minus = false;
                    num = 0;
                }else if(c == ','){
                    if(s.charAt(left - 1) != ']' && s.charAt(left - 1) != '['){
                        if(minus)
                            num *= -1;
                        NestedInteger list = stack1.pop();
                        list.add(new NestedInteger(num));
                        num = 0;
                        minus = false;
                        stack1.push(list);
                    }
                }else if(s.charAt(left) == '-'){
                    minus = true;
                }else{
                    num = num * 10 + (s.charAt(left) - '0');
                }
                left++;
            }
            if(minus)
                num *= -1;
            if(stack1.isEmpty())
                return new NestedInteger(num);
            return stack1.pop();
        }
    }

Log in to reply
 

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