【题目描述】Given a string containing just the characters’(‘and’)’, find the length of the longest valid (well-formed) parentheses substring.
For"(()", the longest valid parentheses substring is"()", which has length = 2.
Another example is")()())", where the longest valid parentheses substring is"()()", which has length = 4.
【考查内容】栈,字符串
//维护一个栈,里面保存'('的下标,每次进入一个')'时,栈弹出,ans更新为当前扫描的下标
//与栈顶元素之间的距离(因为中间可能有些括号已经被消掉了),因为栈可能为空,所以需要
//记录下起始记录点last。
class Solution {
public:
int longestValidParentheses(string s) {
int ans=0,last=-1;
stack<int> st;
for(int i=0;i<s.size();i++){
if(s[i]=='(') st.push(i);
else{
if(!st.size()) last=i;
else{
st.pop();
if(st.size()) ans=max(ans,i-st.top());
else ans=max(ans,i-last);
}
}
}
return ans;
}
};