题目如下:
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.
具体代码如下:
int longestValidParentheses(string s) {
int length = s.length();
if(length<=1)return 0;
int i=0,j=0;
for(int t=0;t<length;t++)
{
if(i!=0&&s[t]==')')
{
j+=2;
i--;
}
if(s[t]=='(')
{
i++;
}
}
return j;
}