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 n = s.size(),mval=0;
vector<int> dp(n,0);
for(int i=n-2;i>=0;--i)
{
if(s[i]=='(')
{
int j=i+1+dp[i+1];
if(s[j]==')')
{
dp[i] = dp[i+1]+2;
if(j+1<n)
dp[i]+=dp[j+1];
}
mval = max(mval,dp[i]);
}
}
return mval;
}
};
本文探讨如何在给定的字符串中找到最长的有效括号子串,通过使用动态规划算法来解决这个问题。
97

被折叠的 条评论
为什么被折叠?



