【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 ...
随机推荐
- DAX Editor VSIX project
DAX Editor is a Visual Studio extension that implements a language service for DAX language for SQL ...
- iOS-Core Animation: 变换
仿射变换 用 CGPoint 的每一列和 CGAffineTransform 矩阵的每一行对应元素相乘再求 和,就形成了一个新的 CGPoint 类型的结果.要解释一下图中显示的灰色元素, 为了能让矩 ...
- db2 查询表前几行
不需要那么多不需要那么多数据的时候使用fetch first xxx rows only数据的时候使用fetch first xxx rows only
- C#网页采集数据的几种方式(WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)
一.通过WebClient获取网页内容 这是一种很简单的获取方式,当然,其它的获取方法也很简单.在这里首先要说明的是,如果为了实际项目的效率考虑,需要考虑在函数中分配一个内存区域.大概写法如下 //M ...
- 项目报错java.lang.ClassNotFoundException: org.common.SessionListener
现象:项目报错java.lang.ClassNotFoundException: org.common.SessionListener,并且myeclipse左侧Package Explorer中项目 ...
- .NET Core开发日志——Controller
在理清路由的工作流程后,接下来需要考虑的,是MVC框架如何生成Controller以及它的生成时机. 根据以前ASP.NET MVC的经验,Controller应该是由一个ControllerFact ...
- Vue 数据响应式原理
Vue 数据响应式原理 Vue.js 的核心包括一套“响应式系统”.“响应式”,是指当数据改变后,Vue 会通知到使用该数据的代码.例如,视图渲染中使用了数据,数据改变后,视图也会自动更新. 举个简单 ...
- PHP之null
null类型 特殊的null值表示一个变量没有值.null类型唯一可能的值是null. 在下列情况下一个变量被认为是null: ①.被赋值为null ②.尚未被赋值 ③被unset(). 语法 nul ...
- [daily][cgroup] 使用cgroup限制进程的CPU占用
参考: https://segmentfault.com/a/1190000008323952 1. 找到cgroup设置的地方. [root@D128 ~]# mount -l |grep cpu ...
- [cloud][sdn] neutron了解
了解 neutron 文档:https://yeasy.gitbooks.io/openstack_understand_neutron/content/ LB讲的不细.DVR讲的不清晰. 读了全文之 ...