您的位置:首页 > 其它

Longest Valid Parentheses(最长合法括号对长度)

2018-01-24 11:38 302 查看


32. Longest Valid Parentheses

DescriptionHintsSubmissionsDiscussSolution

DiscussPick
One

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 longestValidParenthes
9b1a
es(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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐