题目:leetcode
Longest Valid Parentheses
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、先从左到右扫描。遇到 ‘(‘ 则入栈,反之出栈。每当栈为空时,更新一次返回值res!因为此时已经达到最大值。
2、再从右到左扫描一次。为什么还需要从右到左扫描一次?因为从左到右扫描时结束时,若栈不为空,则有可能还有一部分有效的左右括号没有记录到res中。
int longestValidParentheses(string s) {
if(s.size()<2)
return 0;
int res=0,cur=0;
stack<char> sa;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
{
sa.push(s[i]);
cur++;
}
else
{
if(sa.empty())
{
res=max(res,cur);
cur=0;
}
else
{
sa.pop();
cur++;
if(sa.empty())
res=max(res,cur);
}
}
}
if(sa.empty())
return res;
while(!sa.empty())
{
sa.pop();
}
cur=0;
for(int i=s.size()-1;i>=0;i--)
{
if(s[i]==')')
{
sa.push(s[i]);
cur++;
}
else
{
if(sa.empty())
{
res=max(res,cur);
cur=0;
}
else
{
sa.pop();
cur++;
if(sa.empty())
res=max(res,cur);
}
}
}
return res;
}
原文地址:http://blog.csdn.net/bupt8846/article/details/45026389