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[i]代表以s[i]为开头的最长有效括号数。
对于s[i] == '(' :若s[i+1] == ')' ,则dp[i] = 1 + dp[i+2];
若s[i+1]=='('且s[i+dp[i] +1] == ')',则dp[i] = dp[i+1] + 1;
若s[i+1]=='('且s[i+dp[i] +1] != ')',则dp[i] = 0;
同时维护一个max值。
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.size();
if(len == 0 || len == 1) return 0;
if(len == 2 && s[0] != '(' && s[1] != ')') return 0;
int *dp = new int[len + 1];
memset(dp, 0, (len+1) * sizeof(int));
int ret = 0;
for(int i = len - 2; i >= 0; i--) {
if(s[i] == '(') {
//与下一个匹配
if(s[i+1] == ')') {
dp[i] = 2 + dp[i+2];
ret = max(ret, dp[i]);
}
//与下一个不匹配
if(s[i+1] == '(') {
int right = i + 1 + dp[i+1];
if(right < len && s[right] == ')') {
dp[i] = 2 + dp[i+1];
int right = i + dp[i];
if(right < len) dp[i] += dp[right];
ret = max(ret, dp[i]);
}
}
}
}
return ret;
}
};
细节的处理很麻烦,dp有len+1个, i从len - 2开始。代码应该还可以再漂亮一点