//使用栈, 进行判断

class Solution {
public:
int longestValidParentheses(string s) {
stack<int> sta;
int ans=0;
sta.push(-1);
for(int i=0;i<s.length();i++){
if(s[i]=='('){
sta.push(i);
}else{
sta.pop();
if(sta.empty()){
sta.push(i);
}else{
ans=max(ans,i-sta.top());
}
}
}
return ans;
}
};
博客展示了一段用 C++ 编写的代码,使用栈数据结构来解决最长有效括号问题。代码定义了一个 Solution 类,其中的 longestValidParentheses 函数通过栈的操作,遍历字符串并计算出最长有效括号的长度。

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



