【LeetCode每天一题】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 "()()"
思路
这道题一开始我想到的是使用辅助空间栈来解决这个问题,我们在栈中存储下标,然后将匹配的括弧弹出,然后使用当前下标减去栈中最上面元素的下标得到长度,如果栈为空的话,我们移动index表示到当前下标。直到遍历完毕。时间复杂度位O(n),空间复杂度为O(n)
第二种思路是使用动态规划,我们设置一个辅助数组,然后对应元素的下标存储当前的有效长度,一直遍历到最后,返回数组中最长的长度。当遍历到i位置为')'时,我们判断i-1的位置是否是'(',接下来判断i-2是否大于等于0(因为小标为2的前面不会存在可以匹配的字符)。如果i-1的位置不为'(',就会存在'(())'这种情况,所以需要需要对前面的s[i-dp[i-1]-1] 位检查是否是 '('。之后继续判断下标大小是否满足。时间复杂度为O(n),空间复杂度为O(n)。
第一种思路图示

第二种思路的图示




第一种实现代码
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
max_len, index = 0, -1 # 最大长度和下标
stack = [] # 辅助栈
for i , char in enumerate(s): # 从第一个元素开始进行遍历
if char == '(': # 等于'('时添加进栈中
stack.append(i)
else:
if stack: # 先判断栈是否为空
stack.pop() # 淡出与之匹配的'('元素
if stack: # 弹出之后在进行判断
max_len = max(max_len, i - stack[-1]) # 不为空直接减去最上面元素的下标算出最大长度
else:
max_len = max(max_len, i - index)
else:
index = i # 将下标指向当前下标
return max_len
第二种思路实现代码
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) < 2:
return 0
dp = [0]* len(s) # 辅助数组
for i in range(1, len(s)): # 从第一个开始遍历
if s[i] == ')':
if s[i-1] =='(': # 判断前一个是否是'('
if i - 2 >=0: # 判断下标是否大于2
dp[i] = dp[i-2] + 2 # 大于2的话,将前面的最长有效括弧长度加起来。
else:
dp[i]= 2 # 否则就是2
elif (i -dp[i-1]) > 0 and s[i-dp[i-1]-1] == '(': # 对于'))'这种情况进行判定,
if i -dp[i-1] -2 >= 0: # 加上之前最长的有效括弧
dp[i] = dp[i-1] + 2 + dp[i-dp[i-1]-2]
else:
dp[i] = 2+ dp[i-1] # 否则直接用前面一个进行增加。
return max(dp)
【LeetCode每天一题】Longest Valid Parentheses(最长有效括弧)的更多相关文章
- leetcode第31题--Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- [LeetCode] Longest Valid Parentheses 最长有效括号
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- [Leetcode] longest valid parentheses 最长的有效括号
Given a string containing just the characters'('and')', find the length of the longest valid (well-f ...
- [LeetCode] 32. Longest Valid Parentheses 最长有效括号
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- leetcode解题报告 32. Longest Valid Parentheses 用stack的解法
第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
- [leetcode]32. Longest Valid Parentheses最长合法括号子串
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- LeetCode (32) Longest Valid Parentheses
题目 Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
- 【LeetCode每天一题】Valid Parentheses(有效的括弧)
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- leetcode解题报告 32. Longest Valid Parentheses 动态规划DP解
dp[i]表示以s[i]结尾的完全匹配的最大字符串的长度. dp[] = ; ; 开始递推 s[i] = ')' 的情况 先想到了两种情况: 1.s[i-1] = '(' 相邻匹配 这种情况下,dp ...
随机推荐
- 在PowerShell中使用Vim
1.需要去Vim官网下载并安装一个可运行于Win8系统的执行文件(ftp://ftp.vim.org/pub/vim/pc/gvim74.exe). 2.设置PowerShell环境,使能“allow ...
- Linux 更新vim
https://blog.csdn.net/linuxnews/article/details/52938583 https://blog.csdn.net/nzyalj/article/detail ...
- C语言复制图片文件
以下代码将文件一的图片复制到文件二中 #include<stdio.h> #include<stdlib.h> int main() { char ch; char fname ...
- day5 五、数字类型、字符串,列表类型的基本操作和内置方法
一.可变与不可变 可变:值改变,但是id不变,证明就是在改变原值,是可变类型.它的原理是在内存里有一个值,然后这个值发生了改变,意为id地址是同一个,没有变化 # l=['a','b'] # prin ...
- 省一行是一行:在if语句中使用C# 7.0的模式匹配
C# 7.0的模式匹配(Pattern Mathing)不仅可以节省代码,而且可以让代码更流畅(Fluent),今天又在实际开发中体会了一下. 不用模式匹配的代码,需要先获取返回值,然后用if进行判断 ...
- io 流操作hdfs
hdfs 文件上传 本地 --------> 文件系统对象 --------> hdfs 文件系统 输入流 ...
- 使用c#反射实现接口可视化调试页面
直接上代码,引用CommTools.dll.包括aspx显示页面和aspx.cs获取反射数据源代码 using System; using System.Collections.Generic; us ...
- django--admin组件
一,激活管理工具(一般建立工程已创建) 1,setting.py 中安装子应用 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.a ...
- linux基本介绍和使用
基本介绍 Linux入门教程 快捷键 linux 快捷键 用户及用户组 linux之用户和用户组
- 1、python同级目录及子目录模块引入
2个模块在同一个包内时(即引入和被引入的2个py文件在同一个目录下),直接引入模块名 1.引入与被引入模块或包在同一目录下时,直接引入模块名或者包名import modulename.py或者impo ...