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的思想,用d[i]表示从第i个位置开始匹配的长度,那么对于第i个来说,如果它是右括号的话,那么这个位置就是0,如果是做括号的话,那么就要跳过第i+1匹配的最长长度的位置来到j,看位置j是不是右括号,其次还要加上位置j+1的位置的匹配长度。
class Solution {
public:
int longestValidParentheses(string s) {
if (s.length() == 0) return 0;
int ans = 0;
int *d = new int[s.length()];
for (int i = 0; i < s.length(); i++)
d[i] = 0;
d[s.length() - 1] = 0;
for (int i = s.length() - 2; i >= 0; i--) {
if (s[i] == ')')
d[i] = 0;
else {
int j = i + 1 + d[i + 1];
if (j < s.length() && s[j] == ')') {
d[i] = d[i+1] + 2;
if (j + 1 < s.length())
d[i] += d[j+1];
}
}
ans = max(ans, d[i]);
}
return ans;
}
};