您的位置:首页 > 其它

Longest Valid Parentheses

2015-06-22 02:02 281 查看
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 n = s.length();
int result = 0;
if (n < 2)
{
return 0;
}

int buf[n+1];
memset(buf, 0, (n+1)*sizeof(int));
int count = 0;
for (int i = 1; i <= n; i++)
{
if (s[i-1] == '(')
{
count++;
}
else if (count > 0)
{
count--;
buf[i] = 2;
if (s[i-2] == ')')
{
buf[i] += buf[i-1];
}
buf[i] += buf[i-buf[i]];
if (buf[i] > result)
{
result = buf[i];
}
}
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: