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.
Subscribe to see which companies asked this question
经常遇到的是“验证字符串是否是有效的括号“
这道题目,找出最长的,
用栈来保存上一个左边界的下标,在扫描的过程中,遇到左括号,将下标压入,遇到右括号的时候,弹出栈的左括号下标,并且重新计算一次长度
有可能在遇到右括号的时候,弹出之后,栈为空,此时计算长度的时候需要+1 样例:“()“
class Solution {
public:
int longestValidParentheses(string s) {
int len=s.length();
if(len==0) return 0;
stack<int> st;
int max_=0,first=0;
for(int i=0;i<len;i++){
if(s[i]=='('){
st.push(i);
}
else{
if(!st.empty() && s[st.top()]=='('){
st.pop();
first=st.empty()? (-1):st.top();
if(max_<(i-first)) max_=i-first;
}
else{
st.push(i);
}
}
}
return max_;
}
};