Longest Valid Parentheses

来源:互联网 发布:淘宝上卖的vr怎么样 编辑:程序博客网 时间:2024/05/29 19:45

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.

一维DP。

dp[i]表示[i, n-1]的最长距离,所以i从n-2开始逆向dp。

如果s[i]=‘(’,那么跳过中间dp[i+1] 已经求出的最长距离,到 j=i+1+dp[i+1],如果dp[j]为‘)’且j<n,那么dp[i]=dp[i+1]+2.

接下来还需要一步计算:如果j+1<n,[i, j]已经求出了最大距离,还需要加上dp[j+1]. 相当于最终的值=新匹配的()-> 2+dp[i+1]+dp[j+1]


int longestValidParentheses(string s){    int dp[65536];    int longest=0;    int n=s.size();    memset(dp, 0, 65536);    for(int i=n-2; i>=0; i--)    {        if(s[i]=='(')        {            int j=i+1+dp[i+1];            if(j<n && s[j]==')')            {                dp[i]=dp[i+1]+2;                if(j+1<n)                    dp[i]+=dp[j+1];            }        }        longest=max(longest, dp[i]);    }    return longest;}


0 0
原创粉丝点击