Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation: The longest valid parentheses substring is"()()"
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st; // 用于存储位置信息
int last=-1; // 用于记录最前面的有效位置
int res=0;
for(int i=0;i<s.size();++i){
if(s[i]=='('){
st.push(i);
}else{
if(st.empty()){ // 以)开头
last=i;
}else{
st.pop(); // ) 弹出(
if(st.empty()){ // 弹出后为空了
res=max(res,i-last);
}else{ // 弹出后不是空的 "((((((()"
res=max(res,i-st.top());
}
}
}
}
return res;
}
};