Java Using stack


  • 0
    V
    class Solution {
        public NestedInteger deserialize(String s) {
            if (s.charAt(0) != '[') return new NestedInteger(Integer.parseInt(s));
            Stack<NestedInteger> stk = new Stack<>();
            stk.push(new NestedInteger());
            int i = 1, n = s.length();
            char[] A = s.toCharArray();
            while(i < n - 1) {
                if (A[i] == '[') {
                    stk.push(new NestedInteger());
                    i++;
                } else if (A[i] == ']') {
                    NestedInteger inner = stk.pop();
                    stk.peek().add(inner);
                    i++;
                } else if (A[i] == ',') {
                  i++;  
                } else {
                    boolean neg =  (A[i] == '-');
                    if (neg) i++;
                    int val = 0;
                    while(i < n && number(A[i])) {
                        val = val * 10 + A[i++] - '0';
                    }
                    if (neg) val *= -1;
                    stk.peek().add(new NestedInteger(val));
                }
            }
            
            return stk.pop();
        }
        
        private boolean number(char c) {
            return c - '0' <= 9 && c - '0' >= 0;
        }
    }
    

Log in to reply
 

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