Simple Java Iterative Solution


  • 1
    H

    I like this simple version.

    public class Solution {
    
        public NestedInteger deserialize(String s) {
            if (s.charAt(0) != '[') {
                return new NestedInteger(Integer.parseInt(s));
            }
            Deque<NestedInteger> stack = new LinkedList<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '[') { // start a new NestedInteger
                    stack.push(new NestedInteger());
                } else if (c == ']' && stack.size() > 1) { // end, check if need to add curr to upper level
                    NestedInteger n = stack.pop();
                    stack.peek().add(n);
                } else if (Character.isDigit(c) || c == '-') { // is number, parse it, then add it to upper level
                    boolean isNegative = false;
                    if (c == '-') {
                        isNegative = true;
                        i++;
                    }
                    int num = s.charAt(i) - '0';
                    while (i + 1< s.length() && Character.isDigit(s.charAt(i + 1))) {
                        num = num * 10 + (s.charAt(i + 1) - '0');
                        i++;
                    }
                    NestedInteger ni = new NestedInteger(isNegative ? -num : num);
                    stack.peek().add(ni);
                }
            }
            return stack.pop();
        }
    }
    

Log in to reply
 

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