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.Solution:
int longestValidParentheses(string s) {
int n = s.size();
vector<int> dp(n+1, 0);
int maxv = 0;
for(int i = n-2; i>=0;i--)
{
if(s[i]=='(')
{
int j = i+ dp[i+1]+1;
if(j<n&&s[j]==')')
dp[i] = 2 + dp[i+1] + dp[j+1];
maxv = max(dp[i], maxv);
}
}
return maxv;
}
No comments:
Post a Comment