It's my solution with 2 stacks, share with u


  • 0
    Z
        public  int longestValidParentheses(String s) {
            char [] chars = s.toCharArray();
            Stack<Character> temp = new Stack<Character>();
            Stack<Integer> temp1 = new Stack<Integer>();
            int max = 0;
            temp1.push(0);
            for(int i=0;i<s.length();i++)
            {
                if(chars[i]=='(')
                {
                    temp1.push(0);
                    temp.push('(');
                }
                if(chars[i]==')')
                {
                    if(!temp.isEmpty())
                    {
                        if(temp.peek()=='(')
                        {
                            temp.pop();
                            temp1.push(temp1.pop()+temp1.pop()+2);
                            if(temp1.peek()>max)
                                max = temp1.peek();
                        }
                        else
                        {
                            temp1.push(0);
                            temp.push(')');
                        }
                    }
                    else
                    {
                        temp.push(')');
                        temp1.push(0);
                    }
                }
            }
            return max;
        }

Log in to reply
 

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