Clear java solution


  • 0
    M
    public NestedInteger deserialize(String s) {
            Stack<NestedInteger> stack = new Stack<>();
            stack.push(new NestedInteger());
            String str = "";
            for(int i=0; i<s.length(); i++) {
                char c = s.charAt(i);
                switch(c) {
                    case '[': stack.push(new NestedInteger());
                              break;
                              
                    case ']': 
                              NestedInteger ni = stack.pop();
                              if(str.length() > 0) {
                                  ni.add(new NestedInteger(Integer.parseInt(str)));
                                  str = "";
                              }
                              if(!stack.isEmpty()) {
                                  stack.peek().add(ni);
                              }
                              break;
                    case ',': 
                              if(str.length() > 0) {
                                  stack.peek().add(new NestedInteger(Integer.parseInt(str)));
                                  str = "";
                              }
                              break;
                    default: 
                          str = str+c;
                }
            }
            if(str.length() > 0) {
                stack.peek().add(new NestedInteger(Integer.parseInt(str)));
            }
            return stack.peek().getList().get(0);
        }
    '''

Log in to reply
 

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