stack压下标
class Solution {
public:
int longestValidParentheses(string s) {
int N = s.length();
stack<int> S;
for(int i=0;i<N;i++){
if(S.empty()) S.push(i);
else{
if(s[i] == ')' && s[S.top()] == '(') S.pop();
else S.push(i);
}
}
int ans = 0;
int R = N;
while(!S.empty()){
ans = max(ans,R-S.top()-1);
R = S.top();
S.pop();
}
ans = max(ans,R-0);
return ans;
}
};
本文介绍了一种使用栈解决最长有效括号子串问题的方法。通过遍历输入字符串并利用栈来跟踪未配对的左括号位置,该算法能够高效地找出最长的有效括号子串长度。

8万+

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



