#32 Longest Valid Parentheses——Top 100 Liked Questions

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

"""

第一次:使用栈,找到所有有效的括号,并且保存其索引。将索引按照递增顺序排列,找其中连续索引最长的序列长度就是所求。求连续索引最长的序列长度的程序,完全就是凑出来的o(╯□╰)o
"""

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s or s ==')': return 0
        stack = []
        index = []
        res = []
        for i, b in enumerate(s):
            if b == '(':
                stack.append(b)
                index.append(i)
            if b == ')':
                if not stack:
                    continue
                else:
                    check = stack.pop()
                    ind = index.pop()
                    if check == '(':
                        res.append(ind)
                        res.append(i)
  
        res.sort()
        count = 0
        left = 0
        for j in range(len(res) - 1):
            if res[j] + 1 == res[j + 1]:
                if j != len(res) - 2:
                    continue
                else:
                    tmp = j + 1 - left + 1
                    return max(count, tmp)

            tmp = j - left + 1
            left = j + 1
            count = max(tmp, count)     
        return count

"""

Runtime: 60 ms, faster than 18.61% of Python online submissions for Longest Valid Parentheses.

Memory Usage: 12.9 MB, less than 5.55% of Python online submissions for Longest Valid Parentheses.

"""

"""

第二次:抄网上代码,动态规划解法,不懂啊,主要分两种情况:1)以‘)’结尾;2)以‘))’结尾

""" 

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        
        if len(s) == 0:
            return 0
        n = len(s)
        dp = [0] * n
        res = 0
        for i in range(n):
            if i > 0 and s[i] == ')':
                if s[i - 1] == '(':
                    dp[i] = dp[i -2] + 2
                elif s[i - 1] == ')' and i - dp[i - 1] - 1 >= 0 and s[i - dp[i-1] - 1] == '(':
                    dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
            if res < dp[i]:
                res = dp[i]
        return res

"""

Runtime: 40 ms, faster than 99.96% of Python3 online submissions for Longest Valid Parentheses.

Memory Usage: 13.3 MB, less than 9.36% of Python3 online submissions for Longest Valid Parentheses.

"""

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值