Why my solution always TLE


  • 0
    L

    I think it's a O(n) solution,but it cant pass.

        public int longestValidParentheses(String s) {
            int len=s.length();
            if(len<2)return 0;
            int[] stack=new int[1000000];
            int[] stackb=new int[1000000];
            int depth=0;
            int max=0;
            for(int i=0;i<len;i++){
                if(stackb[depth]<0&&s.charAt(i)==')'){
                    stack[depth-1]+=2+stack[depth];
                    stack[depth--]=0;
                    max=Math.max(stack[depth],max);
                }else{
                    stackb[++depth]=s.charAt(i)=='('?-1:1;
                }
            }
            return max;
        }
    

  • 0
    B

    Why do you allocate such a large array? Is it necessary? You should also take allocation overhead into consideration. You could check my code if you like. https://discuss.leetcode.com/topic/69836/share-my-concise-java-code


Log in to reply
 

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