385. Mini Parser

Link

Solution

這題有點難,做法看起來很簡單,但其實中間用到很多技巧達到這樣的結果

 public NestedInteger deserialize(String s) {
        if (!s.startsWith("[")) {
             return new NestedInteger(Integer.valueOf(s));
        }
        Stack<NestedInteger> stack = new Stack<>();
        NestedInteger cur = new NestedInteger();
        stack.push(cur);
        //一開始的[先不算,所以start = 1,
        int start = 1;
        for(int i = 1; i < s.length(); i++){
            char c = s.charAt(i);
            if(c == '['){
                start = i+1;
                NestedInteger ni = new NestedInteger();
                stack.peek().add(ni);
                stack.push(ni);
            }
            else if( c == ']' || c == ','){
                if(i > start){
                    stack.peek().add(new NestedInteger(Integer.valueOf(s.substring(start, i))));
                }
                start = i+1;
                if(c == ']') stack.pop();
            }
            
        }
        return cur;
    }

Last updated

Was this helpful?