Problem nesting the inner most integer (Java)


  • 0
    Z
    public class Solution {
        public NestedInteger deserialize(String s) {
            NestedInteger ans = new NestedInteger();
            int begin = 1;
            int end = s.length()-1;
            if (s.contains("[")){
                    char[] cs = s.toCharArray();
                    String temp;
                    if(!s.substring(1,end).contains("[")){
                        ans.setInteger(Integer.valueOf(s.substring(1,end)));
                        // System.out.println(ans);
                        return new NestedInteger(Integer.valueOf(s.substring(1,end)));
                    }
                        // System.out.println(s);
    
                    for(int i = 1; i < s.length()-1; i++){
                        if(cs[i] == ','){
                            ans.add(deserialize(s.substring(1,i)));
                        }
                        else if(cs[i] == '['){
                            ans.add(deserialize(s.substring(i, end)));
                            break;
                        }
                        
                        
                    }
    
                    return ans;
    
            }
            return new NestedInteger(Integer.valueOf(s));
            
    
        }
    }
    

    Above is my code, I tested it with "[123,[456,[789]]]" and "[123,[456,[789,[101]]]]", but the result was like [123,[456,789]] or [123,[456,[789,101]]] so the inner most value was not wrapped in NestedInteger...

    ans.add(deserialize(s.substring(i, end))); 
    

    I think deserialize should return a NestedInteger, but I don't know why it got something like [456,789]...
    Can anyone help me with this? THANK YOU SO MUCH!!


  • 0

    @zxiang77
    If the String contains '[' than it means this is List. So, Instead of

    ans.setInteger(Integer.valueOf(s.substring(1,end)));
    return new NestedInteger(Integer.valueOf(s.substring(1,end)));
    

    You have to do something like this

    ans.add(new NestedInteger(Integer.valueOf(s.substring(1,end))));
    return ans;
    

Log in to reply
 

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