32. Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
解题思路:借助栈把所有能匹配的括号先弹出,栈内记录的是每个不能匹配的括号的下标。而每两个之间的都是能匹配的,所以求差值的最大值即为所求。
class Solution { public: int longestValidParentheses(string s) { int num=0,ans=0; stack<int>st; for(int i=0;i<s.length();i++){ if(s[i]=='(')st.push(i); else { if((!st.empty())&&s[st.top()]=='(')st.pop(); else st.push(i); } } if(st.empty())ans=s.length(); else{ int a=s.length(),b=0; while(!st.empty()){ b=st.top();st.pop(); ans=max(ans,a-b-1); a=b; } ans=max(ans,a); } return ans; } };