Simple Java Recursive Solution O(n) [16ms]


  • 0
    public class Solution {
        public NestedInteger deserialize(String s) {
            NestedInteger result = deserialize(s, new Wrapper());
            return (result.getList().isEmpty()) ? result : result.getList().get(0);
        }
        
        private NestedInteger deserialize(String s, Wrapper w) {
            NestedInteger result = new NestedInteger();
            while(w.i < s.length()) {
                char c = s.charAt(w.i);
                if(c == '[') {
                    w.i++; 
                    result.add(deserialize(s, w));
                } else if(c == ']') {
                    w.i++; break;
                } else if(c == ',') {
                    w.i++;
                } else {
                    StringBuilder builder = new StringBuilder();
                    while(w.i < s.length() && (((c = s.charAt(w.i)) == '-') || (c >= '0' && c <= '9'))) {
                        builder.append(c); w.i++;
                    }
                    result.add(new NestedInteger(Integer.parseInt(builder.toString())));
                }
            }
            return result;
        }
        
        class Wrapper { int i = 0; }
    }
    

Log in to reply
 

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