Easy solution using stack.


  • 0
    H
    public class Solution {
        public NestedInteger deserialize(String s) {
            if(s.charAt(0) != '[') {
            	return new NestedInteger(Integer.parseInt(s));
            }
    
            Stack<NestedInteger> stack = new Stack<>();
    
            int  i = 0;
            NestedInteger pre = new NestedInteger();
            NestedInteger curr = null;
            while(i < s.length()) {
            		char c = s.charAt(i);
            		if(Character.isDigit(c) || c == '-') {
            			int j = i+1;
            			while(j < s.length() && Character.isDigit(s.charAt(j))) j++;
            			curr.add(new NestedInteger(Integer.parseInt(s.substring(i, j))));		
            			i = j;
            		}
            		else if(c == '[') {
            			stack.push(curr);
            			curr = new NestedInteger();
            			i++;
            		}
            		else if(c == ']') {
            			NestedInteger temp = stack.pop();
            			if(temp != null ) temp.add(curr);
            			curr = temp == null?curr:temp;
            			i++;
            		}
                    else i++;
            }
            return curr;
        }
    }
    
    

Log in to reply
 

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