32. 最长有效括号
给你一个只包含 '('
和 ')'
的字符串,找出最长有效(格式正确且连续)括号子串的长度。
示例 1:
输入:s = "(()"
输出:2
解释:最长有效括号子串是 "()"
示例 2:
输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"
示例 3:
输入:s = ""
输出:0
提示:
0 <= s.length <= 3 * 104
s[i]
为'('
或')'
解法:
栈
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int MAX = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') {
st.push(i);
}
else {
st.pop();
if (st.empty()) {
st.push(i);
}
else {
MAX = max(MAX, i - st.top());
}
}
}
return MAX;
}
记数
int longestValidParentheses(string s) {
int left = 0;
int right = 0;
int leftMax = 0;
int rightMax = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') {
left++;
}
else {
right++;
}
if (left == right) {
leftMax = max(left * 2, leftMax);
}
else if (left < right) {
left = right = 0;
}
}
left = right = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '(') {
left++;
}
else {
right++;
}
if (left == right) {
rightMax = max(right * 2, rightMax);
}
else if (right < left) {
left = right = 0;
}
}
return max(leftMax, rightMax);
}
动态规划
int longestValidParentheses(string s) {
int MAX = 0;
vector<int> dp(s.size(), 0);
for (int i = 1; i < s.size(); i++) {
if (s[i] == ')') {
if (s[i - 1] == '(') {
dp[i] = 2 + (i >= 2 ? dp[i - 2] : 0);
}
else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') {
dp[i] = 2 + dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0);
}
MAX = max(MAX, dp[i]);
}
}
return MAX;
}