static int x=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0, start = 0;//start变量用来记录合法括号串的起始位置
stack<int> st;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(')
st.push(i);
else if (s[i] == ')') {
if (st.empty())
start = i + 1;
else {
st.pop();
// 此时栈顶为最近的没有配对的左括号 eg.(()()() 栈顶为(
// 如果栈为空,则表示从start开始 括号全部配对成功 eg.((())) 栈顶为空
res = st.empty() ? max(res, i - start + 1) : max(res, i - st.top());
}
}
}
return res;
}
};版权声明:本文为wbb1997原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。