[LeetCode]032-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.

Solution:
思路,采用动态规划来做。字符串长度为length
假设dp[i]是从i下标到length-1(最后)的最长连续合法子串。
从length-2开始算起,从后往前。dp[length-1] = 0。

现在假设一个情境计算dp[i]。
1、如果dp[i] = ‘)’。没必要计算了,后面肯定没有匹配的。
2、如果dp[i] = ‘(‘。那就要计算了,首先往后移dp[i+1](可能为0)个位置,到j = i + dp[i+1] +1这个下标。然后比较dp[j]是否为’)’。如果是则匹配成功,dp[i] = dp[i+1] + 2。要满足j

int longestValidParentheses(string s) 
    {
        int n = s.size();
        int* dp = new int[n];
        int maxlength = 0;
        memset(dp,0,sizeof(int)*n);

        for(int i = n-2;i>=0;i--)
        {
            if(s[i] == '(')
            {
                int j = i+dp[i+1]+1;
                if( j < n && s[j] == ')')
                {
                    dp[i] = dp[i+1] + 2;
                    if(j+1 < n)
                        dp[i] += dp[j+1];
                }
            }
            if(dp[i] >= maxlength)
                maxlength = dp[i];
        }
        return maxlength;
    }

你可能感兴趣的:(LeetCode)