Straightforward Java Solution


  • 0
    R
    public class Solution {
        public NestedInteger deserialize(String s) {
            if(s == null || s.length() == 0) {
                return new NestedInteger();
            }
            
            NestedInteger result = null;
            Stack<NestedInteger> stack = new Stack<>();
            int currNum = 0;
            int sign = 1;
            
            NestedInteger currNested = null;
            int i = 0;
            while(i < s.length()) {
                char curr = s.charAt(i);
                if(curr == '[') {
                    if(currNested != null) {
                        stack.push(currNested);
                    }
                    NestedInteger newNested = new NestedInteger();
                    currNested = newNested;
                    i++;
                }
                else if(curr == ']') {
                    if(stack.isEmpty()) {
                        result = currNested;
                        break;
                    }
                    else{
                        stack.peek().add(currNested);
                        currNested = stack.pop();
                    }
                    i++;
                }
                else if(curr == ',') {
                    i++;
                }
                else{
                    sign = 1;
                    
                    if(s.charAt(i) == '-') {
                        sign = -1;
                        i++;
                    }
                    int beginIndex = i;
                    while(i < s.length() && Character.isDigit(s.charAt(i)) ) {
                        i++;
                    }
                    
                    int num = Integer.parseInt(s.substring(beginIndex, i));
                    num = num * sign;
                    if(currNested == null) {
                        currNested = new NestedInteger();
                        currNested.setInteger(num);
                        result = currNested;
                    }
                    else{
                        currNested.add(new NestedInteger(num));
                    }
                }
                
            }
            
            return result;
        }
    }
    

Log in to reply
 

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