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的方法还是用的不够熟练。 目前用到的DP的方法基本上有几种; 一维:dp[i],一般用来表示加入第i个元素后,与前i-1个元素之间的递推关系。或者以第i个元素为结尾的递推关系。 二维:dp[i][j],一般用来处理字符串或者矩阵。遇到字符串或者矩阵处理时需要用到这些。或者题目中给定了限定条件K,比如要求在K的前提下要实现结果与算法。 三维:dp[i][j][k],这种一般用于在字符串或者矩阵中,给定了限定条件K。
class Solution {
public:
int longestValidParentheses(string s) {
if (s.length() <= 1 ) return 0 ;
int curMax = 0 ;
vector<int> end (s.size(),0 );
for (int i=1 ; i < s.length(); i++){
if (s[i] == ')' ){
if (s[i-1 ] == '(' ){
end [i] = (i-2 ) >= 0 ? (end [i-2 ] + 2 ) : 2 ;//dp[i] = dp[i-2 ] + 2 ;
curMax = max(end [i],curMax);
}
else { // if s[i-1 ] == ')' , combine the previous length.
if (i-end [i-1 ]-1 >= 0 && s[i-end [i-1 ]-1 ] == '(' ){
end [i] = end [i-1 ] + 2 + ((i-end [i-1 ]-2 >= 0 )?end [i-end [i-1 ]-2 ]:0 );
curMax = max(end [i],curMax);
}
}
}
//else if s[i] == '(' , skip it, because longest[i] must be 0
}
return curMax;
}
/*
int longestValidParentheses(string s) {
int n = s.size();
int res = 0 ;
vector<bool> flag(n,false );
vector<vector<bool>> dp(n,flag);
for (int i = 0 ; i < n;i++){
dp[i][i] = false ;
}
for (int k = 1 ;k<=n-1 ;k++){
for (int i = 0 ;i+k < n;++i){
if (s[i] == '(' &&s[i+k] == ')' ){
if (k == 1 ){
dp[i][i+k] = true ;
}else {
dp[i][i+k] = dp[i][i+k]||dp[i+1 ][i+k-1 ];
for (int j = i;j < i+k;j++){
dp[i][i+k] = dp[i][i+k]||(dp[i][j]&&dp[j+1 ][i+k]);
}
}
}
if (dp[i][i+k]){
res = max(res,k+1 );
}
}
}
return res;
}*/
/*超时的动态规划
int longestValidParentheses(string s) {
int n = s.size();
int res = 0 ;
vector<bool> flag(n,false );
vector<vector<bool>> dp(n,flag);
for (int i = 0 ; i < n;i++){
dp[i][i] = false ;
}
for (int k = 1 ;k<=n-1 ;k++){
for (int i = 0 ;i+k < n;++i){
if (s[i] == '(' &&s[i+k] == ')' ){
if (k == 1 ){
dp[i][i+k] = true ;
}else {
dp[i][i+k] = dp[i][i+k]||dp[i+1 ][i+k-1 ];
for (int j = i;j < i+k;j++){
dp[i][i+k] = dp[i][i+k]||(dp[i][j]&&dp[j+1 ][i+k]);
}
}
}
if (dp[i][i+k]){
res = max(res,k+1 );
}
}
}
return res;
}*/
};