题目:
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.
思路:
这题存在最优子结构,即如果前面子字符串的是有效的,则后面的有效字符串包括前面的部分。
我们可以用一个数组DP来存储每个单括号对应的有效括号个数,则有下面的关系:
事件复杂度:O(n)
class Solution
{
public:
int longestValidParentheses(string s)
{
int size=s.size();
if(size<2) return 0;
int left=0,max=0;
vector<int> DP(size,0);
for(int i=0;i<size;i++)
{
if(s[i]=='(') left++;
else if(left>0)
{
left--;
if(s[i-1]=='(')
DP[i]=((i-2)>0?DP[i-2]+2:2);
else if(s[i-1]==')'&&s[i-DP[i-1]-1]=='(')
DP[i]=DP[i-1]+2+((i-DP[i-1]-2)>=0?DP[i-DP[i-1]-2]:0);
}
if(DP[i]>max) max=DP[i];
}
return max;
}
};