前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 32 Longest Valid Parentheses DP好题

Leetcode 32 Longest Valid Parentheses DP好题

作者头像
triplebee
发布2018-01-12 15:09:04
4130
发布2018-01-12 15:09:04
举报

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.

就喜欢做这种想法题,

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

https://cloud.tencent.com/developer/article/1019321

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

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

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

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

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

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;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-09-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档