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

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

查看所有标签

猜你喜欢:

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

APP蓝图

APP蓝图

吕皓月 / 清华大学出版社 / 2015-1-1 / 69.00

移动互联网原型设计,简单来说,就是使用建模软件制作基于手机或者平板电脑的App,HTML 5网站的高保真原型。在7.0 之前的版本中,使用Axure RP进行移动互联网的建模也是可以的。比如,对于桌面的网站模型,制作一个1024像素宽度的页面就可以了;现在针对移动设备,制作320像素宽度的页面就好了。但是在新版本的Axure RP 7.0 中,加入了大量对于移动互联网的支持,如手指滑动,拖动,横屏......一起来看看 《APP蓝图》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具