Time Limit Exceeded with Long Input of Length around 200k


  • 0
    K

    Please find my logic as below. It seems that my flow is too slow, but I don't see any significant difference compared to others' solutions...

    while(s.length() > 0) {
                char c = s.charAt(0);
                    
                if (c == '(') {
                    stack.push(c+"");
                    s = s.substring(1);
                } else if (c == ')') {
                	int ssize = stack.size();
                	String last = stack.peek();
                	String secondLast = getSecondLast(stack);
                
                	if (secondLast.equalsIgnoreCase("(")) {
                	   removeSecondLast(stack);
        
                	    if (stack.size() >= 3 && isOperator(getSecondLast(stack))) {
                	         String top = calculateTop(stack);
                	         stack.push(top);
                	    }
                	}
                	s = s.substring(1);
                } else if (c == ' '){
                    s = s.substring(1);
                } else if (c == '+' || c == '-'){
                    stack.push(c+"");
                    s = s.substring(1);
                } else {
                    String nextIntString = getNextIntString(s);
                    
                    if (stack.size() == 0) {
                        stack.push(nextIntString);
                    } else {
                        String last = stack.peek();
                        
                        if (stack.size() >= 2) {
                            if (isOperator(last)){
                                stack.push(nextIntString);
                                String top = calculateTop(stack);
                                stack.push(top);
                            }else{
                                stack.push(nextIntString);
                            }
                        } else {
                            stack.push(nextIntString);
                        }
                    }
                    s = s.substring(nextIntString.length());
                }
            }
            
            if (stack.size() == 0){
                return 0;
            } else{
                return calculateAll(stack);
            }

Log in to reply
 

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