2022-11-21 08:51:23 +00:00
|
|
|
#include "s0032_longest_valid_parentheses.hpp"
|
|
|
|
|
2022-11-30 10:20:36 +00:00
|
|
|
int S0032::longestValidParentheses(string s) {
|
2022-11-21 08:51:23 +00:00
|
|
|
int maxans = 0, n = s.length();
|
|
|
|
vector<int> dp(n, 0);
|
|
|
|
for (int i = 1; i < n; i++) {
|
|
|
|
if (s[i] == ')') {
|
|
|
|
if (s[i - 1] == '(') {
|
|
|
|
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
|
|
|
|
} else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') {
|
|
|
|
dp[i] =
|
|
|
|
dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
|
|
|
|
}
|
|
|
|
maxans = max(maxans, dp[i]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return maxans;
|
|
|
|
}
|