How can I improve my runtime?


  • 0
    S

    My Java submission :

    public class Solution {
        public NestedInteger deserialize(String str) {
            Stack<NestedInteger> stack = new Stack();
            StringBuilder num = new StringBuilder();
            char arr[] = str.toCharArray();
            if(arr[0] != '[')
                return new NestedInteger(Integer.parseInt(str));
            
            for(int i=0; i<arr.length; i++) {
                char ch = arr[i];
                switch(ch) {
                    case '[' :
                        stack.push(null);
                        break;
                        
                    case ',' :
                        if(num.length() != 0) {
                            stack.push(new NestedInteger(Integer.parseInt(num.toString())));
                            num = new StringBuilder();
                        }
                        break;
                        
                    case ']' :
                        NestedInteger curNum = (num.length()!=0)?new NestedInteger(Integer.parseInt(num.toString())):null;
                        if(curNum != null) {
                            stack.push(curNum);
                            num = new StringBuilder();
                        }
                        stack.push(getElementsFromStack(stack));
                        break;
                        
                    default:
                        num.append(ch);
                        
                }
            }
            
            return stack.peek();
        }
        
        private NestedInteger getElementsFromStack(Stack<NestedInteger> stack) {
            NestedInteger list = new NestedInteger();
            List<NestedInteger> aux = new ArrayList<>();
            NestedInteger pop = stack.pop();
            while(pop != null) {
                aux.add(pop);
                pop = stack.pop();
            }
            int l = aux.size();
            for(int i=0; i<l; i++) {
                list.add(aux.get(l-1-i));
            }
            return list;
        }
    }
    

Log in to reply
 

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