/*开一个栈,用来存储'('的下标。每一个')'会匹配一个'('。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
int longestValidParentheses(string s) {
if(s.empty()) return 0;
stack<int> left_idx;
int last(-1), res(0);
for(int i = 0; i < s.size(); ++i){
if(s[i] == '(') left_idx.push(i);
else{
if(left_idx.empty()) last = i;
else{
left_idx.pop();
if(left_idx.empty()) res = max(res, i-last);
else res = max(res, i-left_idx.top());
}
}
}
return res;
}
};LeetCode之Longest Valid Parentheses
最新推荐文章于 2022-09-01 00:56:47 发布
本文介绍了一种使用栈来解决最长有效括号问题的方法。通过遍历字符串并利用栈记录左括号的位置,当遇到右括号时计算有效括号序列长度,最终得到最长的有效括号序列长度。
128

被折叠的 条评论
为什么被折叠?



