A recursive method


  • 0
    M
        public NestedInteger deserialize(String s) {
            if(!s.startsWith("[")){
                return new NestedInteger(Integer.parseInt(s));
            }
            NestedInteger list = new NestedInteger();
            String temp = null;
            int i = 1;
            while(i<s.length()-1){
                //collect the individual integers
                if(s.charAt(i) != '[' && s.charAt(i) != ','){
                    temp = (temp!=null)? temp + s.charAt(i) : ""+s.charAt(i);
                }
                //if its a comma, we have got our integer, add it to the list
                else if(s.charAt(i)==',' && temp != null){
                    list.add(new NestedInteger(Integer.parseInt(temp)));
                    temp = null;
                }
                //we have a sub list that we need to parse
                // a inner while loop to grab the whole sublist to be parsed in
                // another recursive call
                else{
                    int count = 1; 
                    int start = i; i++;
                    String substring = "";
                    while(count!=0){
                        if(s.charAt(i) == ']') count --;
                        if(s.charAt(i) == '[') count ++;
                        i++;
                    }
                    list.add(deserialize(s.substring(start, i)));
                }
                i++;
            }
            // if temp is not null, we haven't added the last integer we parsed
            if(temp != null) list.add(new NestedInteger(Integer.parseInt(temp)));
            return list;
        }
    }```

Log in to reply
 

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