DP-LeetCode32. 最长有效括号

1、题目描述

https://leetcode-cn.com/problems/longest-valid-parentheses/

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度

2、代码详解

情况2 s[i]==  ′  )  ′   

这时,需要看其前面对元素来判断是否有有效括号对。

情况2.1

情况2.2 : 特殊case )()(()))

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        n = len(s)
        if n == 0:
            return 0
        # dp[i] 表示以 i 结尾的最长有效括号
        dp = [0] * n
        res = 0
        for i in range(n):
            # 1:当 s[i] 为 (,dp[i] 必然等于 0,因为不可能组成有效的括号
            # 2:那么 s[i] 为 )
            if i > 0 and s[i] == ")":
                # 2.1 当 s[i-1] 为 (
                if s[i - 1] == "(":
                    dp[i] = dp[i - 2] + 2
                # 2.2 当 s[i-1] 为 ) 并且 s[i-dp[i-1] - 1] 为 (
                elif s[i - 1] == ")" and i - dp[i - 1] - 1 >= 0 and s[i - dp[i - 1] - 1] == "(":
                    dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] - 2]  # 测试用例 )()(()))

                if dp[i] > res:
                    res = dp[i]
        return res

s = ')()(()))'  # 6
S = Solution()
print(S.longestValidParentheses(s))

https://leetcode-cn.com/problems/longest-valid-parentheses/solution/dong-tai-gui-hua-si-lu-xiang-jie-c-by-zhanganan042/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值