32. Longest Valid Parentheses -- leetcode

  • 题目
    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.
    翻译:
    给定一个包含‘(’和‘)’的字符串,找出最长的有效括号匹配子串的长度。
  • 思路
    这道题可以用一维动态规划逆向求解。假设输入括号表达式为String s,维护一个长度为s.length的一维数组dp[],数组元素初始化为0。 dp[i]表示从s[i]到s[s.length - 1]包含s[i]的最长的有效匹配括号子串长度。

  • 代码

class Solution {
public:
    int longestValidParentheses(string s) {
    int len = s.size();
    if (len < 2)return 0;
    vector<int> dp(len + 1, 0);
    int ans = 0;
    for (int i = len - 2; i >= 0; i--)
    {
        if (s[i] == '(')
            if (s[i + 1] == ')')
                dp[i] = (i == len - 2 ? 0 : dp[i + 2]) + 2;
            else
            {
                int k = dp[i + 1] + 1 + i;//
                if (k < len)
                {
                    dp[i] = (s[k] == ')' ? 2 + dp[k + 1] + dp[i + 1]: 0) ;
                }
            }
        ans = max(ans, dp[i]);
    }
    return ans;
}
};
  • 总结
    这道题花了很长时间。问题存在如下1,dp[i]代表的意义设计不合理:刚开始的时候将dp[i]定义为0~i-1中的最优解。但是这样设定以后,想了很久也无法找到递推式。正确的做法是将其设置为包含s[i]的最优解。2 思路不清晰,递推式总是错误。导致vs调试了好多遍,但是每次都有疏忽或错误,wrong answer了好多次。正确的做法是,递推式的逻辑一定要严谨,且自己要清晰,不要脑子里乱成一锅粥。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值