Leetcode 32 longest active brackets

 

 Solution: As the requirement is a string, not a sub-sequence, the interval dp inappropriate here. Consider defining a dp [i] denotes be a s [i] is the effective length of the longest string ending. Discuss classification, if s [i] is the time "(" a, dp [i] = 0;

If s [i] is ")," when considering a front, when s [i-1] when == '(' the dp [i] = 2 + dp [i-2]; if s [i- 1] when == '') to see to s [i-1] is a front end of the string that is not '(' yes dp [i] = 2 + dp [i-1] + dp [ i-dp [i-1] -2];

ac code is as follows:

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;

int dp[100010];
int longestValidParentheses(string s)
{
    int Len = s.length();
    memset(dp,0,sizeof(dp));
    int mx = -1;
    for(int i=1; i<Len; i++)
    {
        if(s[i] == ')')
        {
            if(s[i-1] == '(')
            {
                dp[i] = 2;
                if(i-2>=0)
                    dp[i] += dp[i-2];
            }
            else
            {
                if(s[i-dp[i-1]-1] == '(')
                {
                    dp[i] = 2+dp[i-1];
                    if(i-dp[i-1]-2 >=0)
                        dp[i] += dp[i-dp[i-1]-2];
                }
            }
        }
        mx = max(dp[i],mx);
    }

    for(int i=0;i<Len;i++) cout << dp[i] <<" ";
    cout <<endl;
    return mx;
}
int main ()
{

    string s= "()(())";
    cout << longestValidParentheses(s) <<endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/z1141000271/p/12141612.html