首页 > 其他 > 详细

【栈】Longest Valid Parentheses

时间:2015-04-13 16:43:40      阅读:198      评论:0      收藏:0      [点我收藏+]

题目: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;
    }



【栈】Longest Valid Parentheses

原文:http://blog.csdn.net/bupt8846/article/details/45026389

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!