Concise Java Solution


  • 0

    The following pattern is very generic for similar questions:

    public NestedInteger deserialize(String s) {
        if (s.charAt(0) != '[') {
            return new NestedInteger(Integer.valueOf(s));
        }
    
        Deque<NestedInteger> stack = new ArrayDeque<>();
        NestedInteger curr = new NestedInteger();
        
        Integer num = null;
        int sign = 1;
        
        for (char c : s.toCharArray()) {
            if (c == '[') {
                stack.push(curr);
                curr = new NestedInteger();
                
            } else if (c == ',') {
                if (num != null) {
                    curr.add(new NestedInteger(sign * num));
                }
                num = null;
                sign = 1;
                
            } else if (c == ']') {
                if (num != null) {
                    curr.add(new NestedInteger(sign * num));
                } 
                NestedInteger parent = stack.pop();
                parent.add(curr);
                curr = parent;
                
                num = null;
                sign = 1;
                
            } else if (c == '-') {
                sign = -1;
                
            } else {
                if (num == null) {
                    num = 0;
                }
                num = num * 10 + c - '0';
            }
        }
        
        return curr.getList().get(0);
    }

Log in to reply
 

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