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 result= 0;
int n= s.length();
if(n == 0)
return result;
int begin = 0;
int belance = 0;
for(int i = 0; i < n;i++)
{
if(s[i] == '(')
belance++;
else if(s[i] == ')')
belance--;
if(belance < 0)
{
begin = i+1;
belance = 0;
}
else if(belance == 0)
{
result = max(i-begin+1,result);
}
}
belance = 0;
begin = n-1;
for(int i = n-1; i>=0; i--)
{
if(s[i] == '(')
belance--;
else if(s[i] == ')')
belance++;
if(belance < 0)
{
begin = i-1;
belance = 0;
}
else if(belance == 0)
{
result = max(begin-i+1,result);
}
}
return result;
}
};