My Solution using DFS in Java.


  • 0
    I
        //two cases
        //if integer, then we are making an integer
        //if ], then we are making a list
        //      get rid of outer brackets and parse the CSVs. ie [123,[123,-123]] becomes 123,[123,-123]
        //      we want to send each value in CSV to deserialize, similar to JSON object. We can't use string.split(",")
        //      because it takes into account all commas, even the nested ones.
        //      So I wrote a for loop that checks if the current level is 0. We know the total level of the "parsed" substring is 0,
        //      so we only send values to deserialize(s) when level = 0.
        //      send the last one to deserialize(s) since we won't encounter any more commas.
        
        //      to avoid failing the case where [] occurs, we break if the parsed string is empty. 
        
        public NestedInteger deserialize(String s) {
            if (Character.isDigit(s.charAt(s.length() - 1))) {
                return new NestedInteger(Integer.valueOf(s));
            }
            else {
                NestedInteger res = new NestedInteger();
                int count = 1;
                for (int i = s.length() - 2; i >= 0; i--) {
                    if (s.charAt(i) == ']') count++;
                    else if (s.charAt(i) == '[') {
                        count--;
                        if (count == 0) {
                            String parsed = s.substring(i + 1, s.length() - 1);
                            if (parsed.length() == 0) break;
                            int level = 0;
                            int j = 0;
                            for (int k = 0; k < parsed.length(); k++) {
                                if (parsed.charAt(k) == ',' && level == 0) {
                                    res.add(deserialize(parsed.substring(j, k)));
                                    j = k + 1;
                                } else if (parsed.charAt(k) == '[') level++;
                                else if (parsed.charAt(k) == ']') level--;
                            }
                            if (level == 0) res.add(deserialize(parsed.substring(j, parsed.length()))); 
                        }
                    }
                }
                return res;
            }
        }
    }```

Log in to reply
 

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