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

LeetCode-32-Longest-Valid-Parentheses

作者头像
小二三不乌
发布2018-08-07 17:33:22
3600
发布2018-08-07 17:33:22
举报

LeetCode-32-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.

表示这是一道没有看懂题目的题,看到题目的难度是hard,但是自己的想法很简答,以为直接一个栈就可以了。。 too young啊

提交之后才知道,原来还要解决类似()((()))这类问题,所以这是一个动态规划的问题啊。 昨天看了一下动态规划,我们首先要构建D数组,如下所示的vector longest,负责存下当前第i个的长度。需要考虑的情况如下。 只有当s[i]为)时,才需要判断,如果它的左边是(或者)的情况。 代码如下:

代码语言:javascript
复制
class Solution {
public:
    int longestValidParentheses(string s) {
        if(s.length()<=1)
            return 0;
        vector<int > longest(s.size(),0);
        int curMax=0;
        for(int i=1;i<s.length();++i){
            if(s[i]==')'){
                if(s[i-1]=='('){
                    longest[i]=(i-2>=0?(longest[i-2]+2):2);
                    curMax=curMax>longest[i]?curMax:longest[i];
                }
                else {
                    if(i-longest[i-1]-1>=0&&s[i-longest[i-1]-1]=='('){
                        longest[i]=longest[i-1]+2+((i-longest[i-1]-2>=0)?longest[i-longest[i-1]-2]:0);
                        curMax=curMax>longest[i]?curMax:longest[i];
                    }
            }
            }
        }
        return curMax;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-12,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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