Longest Valid Parentheses
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.
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
int ret = 0;
int top = s.size();
for(int i = 0; i < s.size(); ++i){
if('(' == s.at(i))
st.push(i);
else if(st.empty())
top = i + 1;
else{
top = min(top, st.top());
st.pop();
if(st.empty())
ret = max(ret, i - top + 1);
else
ret = max(ret, i - st.top());
}
}
return ret;
}
};