1.这道题我最开始想到了只有左右括号个数匹配的字符串才是有效括号串,可是总是想不明白,中间有多的不能匹配的’('应该如何解决,后来看题解发现题解正向反向遍历了两边字符串,解决了这个问题,真是妙啊。
class Solution {
public:
int longestValidParentheses(string s) {
int le_brac = 0;
int ri_brac = 0;
int result = 0;
int l = s.length();
for (int i = 0; i < l; i++) {
if (s[i] == ')') {
ri_brac++;
} else {
le_brac++;
}
if (ri_brac > le_brac) {
le_brac = ri_brac = 0;
}
if (ri_brac != 0 && ri_brac == le_brac) {
if (le_brac * 2 > result) result = le_brac * 2;
}
}
le_brac = ri_brac = 0;
for (int i = l - 1; i >= 0; i--) {
if (s[i] == ')') {
ri_brac++;
} else {
le_brac++;
}
if (ri_brac < le_brac) {
le_brac = ri_brac = 0;
}
if (ri_brac != 0 && ri_brac == le_brac) {
if (le_brac * 2 > result) result = le_brac * 2;
}
}
return result;
}
};
2.又去看了题解中的动态规划方法,觉得也很巧妙,就写了一下
class Solution {
public:
int longestValidParentheses(string s) {
int result = 0;
int l = s.length();
int dp[l + 1];
memset(dp, 0, sizeof (dp));
for (int i = 1; i < l; i++) {
if (s[i] == ')') {
if (s[i - 1] == '(') {
if (i - 2 >= 0) {
dp[i] = dp[i - 2] + 2;
} else {
dp[i] = 2;
}
} else {
if (i - 1 - dp[i - 1] >= 0 && s[i - 1 - dp[i - 1]] == '(') {
if (i - 2 - dp[i - 1] >= 0) {
dp[i] = dp[i - 1] + 2 + dp[i - 2 - dp[i - 1]];
}
else {
dp[i] = dp[i - 1] + 2;
}
}
}
}
if (dp[i] > result) result = dp[i];
}
return result;
}
};