Java iterative accepted solution using stack


  • 0
    M
    public class Solution {
        public NestedInteger deserialize(String s) {
            NestedInteger ret = new NestedInteger();
            if(s == null || s.isEmpty()) {
                return new NestedInteger();
            }
            
            Stack<NestedInteger> stack = new Stack<>();
            stack.push(ret);
            int sign = 1;
            for(int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(c == '[') {
                    NestedInteger ni = new NestedInteger();
                    if(!stack.isEmpty()) {
                        stack.peek().add(ni);
                    }
                    stack.push(ni);
                    sign = 1;
                } else if(Character.isDigit(c)) {
                    int num = c - '0';
                    while(i+1 < s.length() && Character.isDigit(s.charAt(i+1))) {
                        num = num * 10 + s.charAt(i+1) - '0';
                        i++;
                    }
                    num = num * sign;
                    sign = 1;
                    stack.peek().add(new NestedInteger(num));
                } else if (c == ',') {
                    continue;
                } else if (c == ']') {
                    stack.pop();
                } else if (c == '-') {
                    sign = -1;
                }
            }
    
            return ret.getList().isEmpty() ? ret : ret.getList().get(0);
        }
    }
    

Log in to reply
 

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