LeetCode-32 New

栏目: 编程工具 · 发布时间: 7年前

内容简介:Given a string containing just the charactersSolution:1.使用栈:

Longest Valid Parentheses

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 "()()"

Solution:

1.使用栈:

首先将-1放入栈中,然后每次遇到 '(' 就将其下标入栈,每遇到 ')' 就出栈,并计算当前有效的字符串长度。当出栈后栈变为空,并将当前下标入栈。并保持记录最长字串。

class Solution:
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_length = 0
        stack = [-1]
        for i in range(len(s)):
            if s[i] == '(':
                stack.append(i)
            else:
                stack.pop()
                if len(stack) == 0:
                    stack.append(i)
                else:
                    max_length = max(max_length, i - stack[-1])
        return max_length

2.动态规划:

声明 dp 数组,长度和字符串总长度一致。dp 数组的第 i 个元素代表以 i 结尾的最长子串的长度。初始 dp全为0。有效子串肯定是以 ')' 结尾,因此分为两种情况:

  1. s[i] = ')' and s[i - 1] = '(' , 此时 dp[i] = dp[i - 2] + 2
  2. s[i] = ')' and s[i - 1] = ')' , 此时 dp[i] = dp[i - 1] + dp[i - dp[i-1] - 2] + 2
class Solution:
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_length = 0
        dp = [0] * len(s)
        for i in range(1, len(s)):
            if s[i] == ')':
                if s[i - 1] == '(':
                    dp[i] = (dp[i - 2] if i >= 2 else 0) + 2
                elif i - dp[i - 1] > 0 and s[i - dp[i - 1] - 1] == '(':
                    dp[i] = dp[i - 1] + (dp[i - dp[i - 1] - 2] if i - dp[i - 1] >= 2 else 0) + 2
                max_length = max(max_length, dp[i])
        return max_length

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Google成功的七堂课

Google成功的七堂课

罗耀宗 / 电子工业出版社 / 2005-7 / 28.00元

Google是全球使用人数最多的搜索引擎,在短短几年内,Google从斯坦福大学的实验室,茁壮成长为举世瞩目的IT业超级巨人,他们的成功绝非偶然,尤其是在网络泡沫破灭,行业一片萧条之际,它的崛起更为IT业带来一缕曙光。作者从趋势观察家的角度,以讲座的形式,向读者讲述Google成功的关键因素:破除因循守旧、不断打破常规,核心技术领先、做出了“更好的捕鼠器”,使得Google在搜索技术方面远远超越对......一起来看看 《Google成功的七堂课》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具