class Solution {
public:
int longestValidParentheses(string s) {
int length = s.size();
if(length < 2) return 0;
int dp[length];
int currentMax = 0;
memset(dp, 0, sizeof(dp));
for(int i=1; i<length; i++) {
if(s[i] == ')') {
if(s[i-1] == '(') {
dp[i] = i-2 >= 0 ? dp[i-2] + 2 : 2;
} else if(i-dp[i-1]-1 >= 0 && s[i-dp[i-1]-1] == '(') {
dp[i] = dp[i-1] + 2 +
(i-dp[i-1]-2 >= 0 ? dp[i-dp[i-1]-2] : 0);
}
currentMax = max(currentMax, dp[i]);
}
}
return currentMax;
}
};
按照Solution中dp方法写的,好多次才过,刚开始是数组越界的检查
后来怎么都不对,别人写得dp用vector就能过,数组就过不了。后来发现memset理解错的。以后注意慎用memset
Solution中其它算法没力气看了...