LeetCode[385] Mini Parser

Given s = "[123,[456,[789]]]",

Return a NestedInteger object containing a nested list with 2 elements:

  1. An integer containing value 123.

  2. A nested list containing two elements:

    1. An integer containing value 456.

    1. A nested list with one element:

      1. An integer containing value 789.

Using Stack

复杂度
O(N), O(N)

思路
每次遇到一个“["就推进去一个nextedinteger,每次碰到一个数字,就在stack.peek().add(number)。每次碰到一个右括号,就把pop()出peek()的nexted integer,并将其压到栈顶的nestedinteger中。

代码

public NestedInteger deserialize(String s) {
    // check the input string first;
    // .... if(s == null) return ..null 
    char[] arr = s.toCharArray();
    if(arr[0] != '[') return new NestedInteger(Integer.parseInt(s));
    Stack<NestedInteger> stack = new Stack<>();
    for(int i = 0; i < arr.length; i ++) {
        char ch = arr[i];
        if(ch == '[') {
            stack.push(new NestedInteger());
        }
        else if(ch == ']' && stack.size() > 1) {
            NestedInteger top = stack.pop();
            stack.peek().add(top);          
        }
        else if(Character.isDigit(ch) || ch == '-') {
            boolean pos = true;
            if(ch == '-') pos = false;
            int num = 0;
            while(i < arr.length && Character.isDigit(arr[i])) {
                num *= 10;
                num += arr[i] - '0';
                i ++;
            }
            // move i back to the integer, [788],
            // otherwise will skip the ']'
            i --;
            stack.peek().add(pos ? num : -num);
        }
    }
    return stack.pop();
}

hellolittleJ17
10 声望11 粉丝