18 ms Java Solution using Stacks


  • 0
    public NestedInteger deserialize(String s) {
            if(null == s) {
                return null;
            }
            
            if(s.length() < 1) {
                return new NestedInteger();
            }
            
            if(s.charAt(0) != '[') {
                return new NestedInteger(Integer.parseInt(s));
            }
            
            int num=0;
            boolean isNumExist = false;
            
            int sign = 1;
            Deque<NestedInteger> nStack = new ArrayDeque<>();
            NestedInteger top = null;
            NestedInteger ns = null;
            
            for(int i=0; i<s.length(); i++) {
                char c = s.charAt(i);
                
                switch(c) {
                    case '[':
                        nStack.push(new NestedInteger());
                        break;
                    
                    case '-':
                        sign = -1;
                        break;
                        
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                        num = num*10 + c - '0';
                        isNumExist = true;
                        break;
                    
                    case ',':
                        if(isNumExist) {
                            ns = nStack.pop();
                            ns.add(new NestedInteger(sign*num));
                            nStack.push(ns);
                        }
                        num = 0;
                        sign = 1;
                        isNumExist = false;
                        break;
                    
                    case ']':
                        ns = nStack.pop();
                        if(isNumExist) {
                            ns.add(new NestedInteger(sign*num));
                            num = 0;
                            sign = 1;
                            isNumExist = false;
                        }
    
                        if(null != nStack.peek()) {
                            top = nStack.pop();
                            top.add(ns);
                            nStack.push(top);
                        } else {
                            nStack.push(ns);
                        }
                        
                        break;
                 }
            }
            
            return nStack.pop();
        }
    

Log in to reply
 

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