Clean Iterative Java Solution using Stack


  • 1
    W
    public class Solution {
        public NestedInteger deserialize(String s) {
            String[] tokens = s.split(",");
            Stack<NestedInteger> stack = new Stack();
            NestedInteger root = new NestedInteger();
            stack.push(root);
            
            for (String token: tokens) {
                int start = 0;
                int end = token.length();
                
                while (token.charAt(start) == '[') {
                    stack.push(new NestedInteger());
                    start++;
                }
                
                NestedInteger topMost = stack.peek();
                
                while (token.charAt(end - 1) == ']') {
                    NestedInteger prevList = stack.pop();
                    stack.peek().add(prevList);
                    end--;
                }
                
                if (start < end) {
                    NestedInteger curInteger = new NestedInteger(Integer.parseInt(token.substring(start, end)));
                    topMost.add(curInteger);    
                }
            }
            
            return root.getList().get(0);
        }
    }
    

  • 0
    K

    @wcyz666
    Wow, its exactly I am looking for a stack solution.. :)


Log in to reply
 

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