题目链接为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.
这道题可以用动态规划来解决
我的想法是算出以每个字符结尾的子串的最长有效括号对的长度.这样会得到比较简单的递推公式
C++代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.length();
int *dp = new int[len + 1];
int max = 0;
dp[0] = 0;
dp[1] = 0;
for(int i = 1; i < len; i++){
if(s[i]==')'){
if(s[i-1]=='('){
dp[i+1] = dp[i-1] + 2;
}
else{
int last = i-dp[i];
if(last > 0 && s[last-1]=='('){
dp[i+1] = dp[last-1] + dp[i] + 2;
}
else {
dp[i+1] = 0;
}
}
}
else {
dp[i+1] = 0;
}
}
for(int i = 1; i <= len; i++){
max = max > dp[i] ? max : dp[i];
}
return max;
}
};