1.题目
给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
示例 1:
输入:s = "(()"
输出:2
解释:最长有效括号子串是 "()"
示例 2:
输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"
示例 3:
输入:s = ""
输出:0
2.解法
通过维护暂未匹配括号栈来解这一题。
#include<stack>
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> q;
int res = 0;
for (int i=0; i < s.length(); i++) {
if (q.empty()) {
q.push(i);
} else if (s[i] == ')' && s[q.top()] == '(') {
int j = q.top();
q.pop();
if (!q.empty())
// 栈不为空,就通过当前索引与q.top(),判断统计当前有效括号索引长度
res = max(res, i-q.top());
else {
// 栈为空,说明都合法,返回index+1
res = i+1;
}
} else {
q.push(i);
}
}
return res;
}
};