Java One Stack - Easy to Understand With Comments


  • 0
    S
    public NestedInteger deserialize(String s) {
            Stack<NestedInteger> nestedStack = new Stack<>();
            NestedInteger result = null;
            
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '[') {
                    nestedStack.push(new NestedInteger());
                }
                else if (Character.isDigit(s.charAt(i)) || s.charAt(i) == '-') {
                    int sign = 1;
                    if (s.charAt(i) == '-') {
                        sign = -1;
                        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++;
                    }
                    if (nestedStack.empty()) return new NestedInteger(sign * num);  //Only single integer exist, no list here, just return
                    NestedInteger curr = nestedStack.pop();
                    curr.add(new NestedInteger(sign * num));
                    nestedStack.push(curr);
                }
                else if (s.charAt(i) == ']') {
                    NestedInteger curr = nestedStack.pop();
                    if (!nestedStack.empty()) {                 //Add to parent nested integer
                        NestedInteger parent = nestedStack.pop();   
                        parent.add(curr);
                        nestedStack.push(parent);
                    } else {                                    //End of string, curr is the final nested integer we want.
                        result = curr;
                    }
                }
            }
            
            return result;
        }
    

Log in to reply
 

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