【Leetcode 32.Longest Valid Parentheses】动态规划

从今天2017.10.15开始记录我的leetcode被虐之旅

毫无疑问,这又是一道凭借我一己之力无法解出的题,并且难度分级是hard级别,我也选择这道题作为我学习DP(Dynamic Programming)的开始吧!

动态规划的一般是从解决小问题开始,选择自底向上(迭代)或者自顶向下(递归)解决问题
而关键问题就是求出状态转移方程

题目描述如下:
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.

由此可以构建一个longest[]数组记录对应下标位置的最长有效括号长度
1. 可知当前s[i] == ‘(‘时,longest[i] = 0;
2. 当s[i] == ‘)’时longest数组才可更新:

此时说明可以找到左括号与当前右括号进行匹配,最后面加上的是匹配位置之前的最长括号长度

if s[i - 1] == ')' and s[i - longest[i-1] - 1] == '(' :
        longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]

最后代码呈现如下:

int longestSubParentheses(string s){
    if (s.length() <= 1)
        return 0;
    //这样初始化,定义了以i下标结尾的最长括号串
    vector<int> longest(s.length(), 0);

    int curMax = 0;
    for (int i = 1; i < s.length(); i++)
        if (s[i] == ')' && s[i - longest[i - 1] - 1] == '(' && i - longest[i - 1] - 1 >= 0)
        {
            longest[i] = longest[i - 1] + 2 + (i - longest[i - 1] - 2) >= 0 ? longest[i - longest[i - 1] - 2] : 0;
            curMax = max(curMax, longest[i]);
        }

    return curMax;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值