I think recursion can simplify the code a bit...


  • 0
    S
    public NestedInteger deserialize(String s) {
        It it = new It(s);
        String firstToken = it.next();
        return firstToken.equals("[") ? deserialize(it) : new NestedInteger(Integer.parseInt(firstToken));
    }
    
    private NestedInteger deserialize(It it) {
        NestedInteger ni = new NestedInteger();
    
        while (it.hasNext()) {
            String token = it.next();
    
            if (token.equals("[")) ni.add(deserialize(it));
            else if (token.equals("]")) return ni;
            else ni.add(new NestedInteger(Integer.parseInt(token)));
        }
    
        return ni;
    }
    
    static class It {
        private int i = 0;
        private String s;
    
        It(String s) {
            this.s = s;
        }
    
        boolean hasNext() {
            return i < s.length();
        }
    
        String next() {
            if (s.charAt(i) == ',') i++; // ignore
            if (s.charAt(i) == '[' || s.charAt(i) == ']') return "" + s.charAt(i++);
    
            String t = "" + s.charAt(i++); // either minus sign or first digit
            while (i < s.length() && Character.isDigit(s.charAt(i)))
                t = t + s.charAt(i++);
    
            return t;
        }
    }

Log in to reply
 

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