Leetcode 32 Longest Valid Parentheses DP好题

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.

就喜欢做这种想法题,

一开始的想法和之前做过的一道括号匹配差不多,用栈。

http://blog.csdn.net/accepthjp/article/details/52370769

记录未匹配的括号位置,然后两两相减找到最大值,过了,但速度并不快。

在discuss中看到有人用DP,恍然大悟!

dp[i]表示以当前位置为终点的最长长度,则只能在)处更新,

如果s[i-1-dp[i-1]]=='(',则说明当前位置可以和i-1-dp[i-1]位置匹配,dp[i]=dp[i-1]+2;

然后还要加上匹配位置之前的最长长度dp[i]+=dp[i-dp[i]];

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


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值