leetcode 32: Longest Valid Parentheses

来源:互联网 发布:电视播放软件破解版 编辑:程序博客网 时间:2024/05/01 01:24

The O(n) stack method: (can still me improved)

class Solution {public:    int longestValidParentheses(string s) {        vector<bool> len(s.length(),false);        stack<int> st;        int res=0;        for(int i=0;i<s.length();i++)        {            if(s[i]=='(')                st.push(i);            else if(!st.empty())            {                len[i]=true;                len[st.top()]=true;                st.pop();            }        }        int max=0;        for(int i=0;i<len.size();i++)        {            if(len[i])            {                max++;                res=max>res?max:res;            }            else            {                max=0;            }        }        return res;    }};

The DP method:

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


0 0
原创粉丝点击