【栈、动态规划】Longest Valid Parentheses

来源:互联网 发布:达内大数据培训靠谱吗 编辑:程序博客网 时间:2024/05/22 05:18

题目: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中。


class Solution {public:    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())                {                    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())                {                    cur=0;                }                else                {                    sa.pop();                     cur++;                    if(sa.empty())                      res=max(res,cur);                }            }        }                    return res;    }};

另一种解法:动态规划,参考http://www.tuicool.com/articles/vUnEbi

class Solution {public:    int longestValidParentheses(string s) {        if(s.size()<=1)            return 0;        vector<int> f(s.size(),0);        int res=0;        for(int i=s.size()-2;i>=0;--i)        {            if(s[i]=='(')            {                int j=i+1+f[i+1];                if(j<s.size() && s[j]==')')                {                    f[i]=f[i+1]+2;                    res=max(res,f[i]);                    if(j+1<s.size())                    {                        f[i]+=f[j+1];                         res=max(res,f[i]);                    }                }                            }        }        return res;    }};




0 0