您的位置:首页 > 其它

LeetCode算法题目:Longest Valid Parentheses

2017-04-06 16:07 295 查看

题目:

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.

分析:

维护一个栈,栈底值为上次匹配失败的位置

首先初始放一个-1入栈代表上次匹配失败的地方为-1

依次扫描字符

若为’(‘,将位置放入栈中

若为’)’,若栈中元素大于1个,则代表有’(‘可匹配,更新最优值,否则更新栈底

显然,对于任意一个部分最长子串,其最后一个字符更新时取的是上一次匹配失败的位置,故所有部分最长子串取得最优结果

代码:

class Solution
{
public:
int longestValidParentheses(string s)
{
stack<int>S;
S.push(-1);
int ans=0;
for(string::size_type i=0;i<s.size();i++)
{
char ch=s[i];
if(ch == '(')
{
S.push(i);
}
else
{
if(S.size()>1)
{
S.pop();
int tmp=S.top();
ans=max(ans,(int)i-tmp);
}
else
{
S.pop();
S.push(i);
}
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法