给你一个只包含 '('
和 ')'
的字符串,找出最长有效(格式正确且连续)括号子串的长度。
示例 1:
输入:s = "(()" 输出:2 解释:最长有效括号子串是 "()"
示例 2:
输入:s = ")()())" 输出:4 解释:最长有效括号子串是 "()()"
示例 3:
输入:s = "" 输出:0
提示:
0 <= s.length <= 3 * 104
s[i]
为'('
或')'
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0;
vector dp(s.length(), 0);
for (int i = 1; i < s.length(); i++)
{
if ( s[i] == '(' ) continue;
int cp = i - dp[i-1] -1;
if( cp < 0 || s[cp] == ')') continue;
if ( cp > 0 ) dp[i] = 2 + dp[i-1] + dp[cp-1];
else dp[i] = 2 + dp[i-1];
res = max(res, dp[i]);
}
return res;
}
};
4ms 81.25%
7.53MB 43.31%