32. 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) {
int l = 0, r = 0;
int ans = 0;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '(')
l++;
else
{
r++;
if(l == r)
ans = max(ans, l * 2);
else if(r > l)
l = r = 0;
}
}
l = r = 0;
for(int i = s.size() - 1; i >= 0; i--)
{
if(s[i] == ')')
r++;
else
{
l++;
if(l == r)
ans = max(ans, l * 2);
else if(l > r)
l = r = 0;
}
}
return ans;
}
};