您的位置:首页 > 其它

[LeetCode]Longest Valid Parentheses

2013-11-28 13:41 381 查看
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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int ret=0,last=-1;
stack<int> left;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(') left.push(i);
else  //s[i]==')'
{
if(left.empty()) last=i;
else
{
left.pop();
if(left.empty()) ret=max(ret,i-last);
else ret=max(ret,i-left.top());
}
}
}
return ret;
}
};


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