栈
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
int ans = 0;
if(s.size() <= 1) return 0;
st.push(-1);
for (int i = 0; i < s.size(); ++i)
{
if(s[i] == '(') {
st.push(i);
}else{
st.pop();
if(st.empty()){//更新断点
st.push(i);
}else{//更新最长子串
ans = max(ans, i - st.top());
}
}
}
return ans;
}
};
题目链接:https://leetcode-cn.com/problems/longest-valid-parentheses/