Really Easy To Understand Java 19ms Recursive Solution Without Stack!!! Beats 82.59%!!!


  • 1
    G
    public NestedInteger deserialize(String s) {
            NestedInteger res = new NestedInteger();
            if (s.length() == 0) return res;
            if (s.charAt(0) != '[') {
                res.setInteger(Integer.parseInt(s));
                return res;
            }
            helper(res, s);
            return res;
        }
        
        public void helper(NestedInteger res, String s) {
            for (int i = 1; i < s.length() - 1; ++i) {
                if (s.charAt(i) == '[') {
                    int start = i;
                    int count = 1;
                    while (count != 0) {
                        i++;
                        if (s.charAt(i) == ']') count--;
                        if (s.charAt(i) == '[') count++;
                    }
                    NestedInteger temp = new NestedInteger();
                    helper(temp, s.substring(start, i + 1));
                    res.add(temp);
                }
                if (Character.isDigit(s.charAt(i)) || s.charAt(i) == '-') {
                    int start = i;
                    while (s.charAt(i) != ',' && s.charAt(i) != ']') i += 1;
                    res.add(new NestedInteger(Integer.parseInt(s.substring(start, i))));
                }
            }
        }

Log in to reply
 

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