Java recursive solution, Beats 99%


  • 0
    J
    class Solution {
        private int parse(char[] chars, int idx, NestedInteger root) {
            int num = 0;
            boolean neg = false;
            boolean hasNum = false;
            while (idx < chars.length) {
                char c = chars[idx++];
                if (c == '[' || c == ']' || c == ',') {
                    if (hasNum) {
                        root.add(neg ? new NestedInteger(-num) : new NestedInteger(num));
                        hasNum = false;
                        neg = false;
                        num = 0;
                    }
                    if (c == ']') return idx;
                    if (c == '[') {
                        NestedInteger next = new NestedInteger();
                        root.add(next);
                        idx = parse(chars, idx, next);
                    }
                } else if (c == '-') neg = true;
                else {
                    num *= 10;
                    num += c - '0';
                    hasNum = true;
                }
            }
            if (hasNum) root.add(neg ? new NestedInteger(-num) : new NestedInteger(num));
            return chars.length;
        }
        public NestedInteger deserialize(String s) {
            NestedInteger root = new NestedInteger();
            if (s.length() == 0) return root;
            char[] c = s.toCharArray();
            parse(c, 0, root);
            return root.getList().get(0);
        }
    }
    

Log in to reply
 

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