Problem 385

Posted by Ruizhi Ma on October 23, 2020

Solution URL

https://leetcode.com/submissions/detail/412410037/

代码

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *     // Constructor initializes an empty nested list.
 *     public NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     public NestedInteger(int value);
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // Set this NestedInteger to hold a single integer.
 *     public void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     public void add(NestedInteger ni);
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
class Solution {
    //ans: https://leetcode-cn.com/problems/mini-parser/solution/java-di-gui-jiu-vansla-by-leetcoder-youzg/
    private char[] c;
    private int idx = 0;

    public NestedInteger deserialize(String s) {
        //corner case
        if(s == null || s.length() == 0) return null;

        //若第一个不是 [
        c = s.toCharArray();
        if(c[0] != '['){
            return new NestedInteger(Integer.valueOf(s));
        }else{//若第一个是 [
            return helper();
        }
    }

    public NestedInteger helper(){
        NestedInteger nest = new NestedInteger();
        int sign = 1;
        int num = 0;
        while(idx < c.length - 1){
            idx++;
            //若为[,则递归
            if(c[idx] == '['){
                nest.add(helper());
            }else if(c[idx] == '-'){
                sign = -1;
            }else if(c[idx] == ','){
                continue;
            }else if(c[idx] == ']'){
                return nest;
            }else{
                num = num * 10 + sign * (c[idx] - '0');
                if(c[idx+1] == ',' || c[idx+1] == ']'){
                    nest.add(new NestedInteger(num));
                    sign = 1;
                    num = 0;
                }
            }
        }
        return null;
    }
}