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

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

查看所有标签

猜你喜欢:

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

算法技术手册

算法技术手册

George T. Heineman、Gary Pollice、Stanley Selkow / 杨晨、李明 / 机械工业出版社 / 2010-3 / 55.00元

《算法技术手册》内容简介:开发健壮的软件需要高效的算法,然后程序员们往往直至问题发生之时,才会去求助于算法。《算法技术手册》讲解了许多现有的算法,可用于解决各种问题。通过阅读它,可以使您学会如何选择和实现正确的算法,来达成自己的目标。另外,书中的数学深浅适中,足够使您可以了解并分析算法的性能。 较之理论而言,《算法技术手册》更专注于应用。《算法技术手册》提供了高效的代码解决方案,使用多种语言......一起来看看 《算法技术手册》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具