您的位置:首页 > 其它

[Leetcode] Longest Valid Parentheses

2013-02-22 04:55 441 查看
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.

#include <stack>
using namespace std;

class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

int maxLength = 0;
int size = s.size();
stack<int> left;
if(size<=0) return 0;
int top = size;

for(int i = 0; i<size; i++)
{
if(s[i]=='(')
{
left.push(i);
}
else
{
if(left.empty())
{
top = i + 1;//指向下一个为")"的index
}
else
{
int tmp = left.top();
top = min(top,tmp);
left.pop();
if(left.empty()) maxLength = max(i-top+1,maxLength);
else maxLength = max(i-left.top(),maxLength); //注意:为什么是left.top()而不是tmp-1呢?考虑"(()()"的情况。
}
}
}

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