Very Simple Java Recursion Coding 14ms


  • 0
    L

    Very Simple Java Recursion Coding

    public class Solution {
        public NestedInteger deserialize(String s) {
            if (s.charAt(0) != '[')
                return new NestedInteger(Integer.parseInt(s));
            NestedInteger res = new NestedInteger();
            int k = 0, start = 1;
            for (int i = 1; i < s.length() - 1; i++) {
                if (s.charAt(i) == '[')
                    k++;
                else if (s.charAt(i) == ']')
                    k--;
                else if (k == 0 && s.charAt(i) == ',') {
                    if (start < i)
                        res.add(deserialize(s.substring(start, i)));
                    start = i + 1;
                }
            }
            if (start < s.length() - 1)
                res.add(deserialize(s.substring(start, s.length() - 1)));
            return res;
        }
    }

  • 0
    V

    Can you explain your solution?


  • 0
    L

    when k is 0 and s.charAt(i) is ',' ,it means s.substring(start, i) is an element of the res and it also is a NestedInteger , So we can use the method to get it , and the start of the next element is i + 1.


Log in to reply
 

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