【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 ...
随机推荐
- 实验一:基于STM32F1的流水灯实验(库函数)
参考原子哥学习程序 条件:实验板STM32103ZET6:固件库STM32F10x_StdPeriph_Lib_V3.5.0:环境MDK5: 目的:了解STM32 的 IO 口如何作为输出使用 :以两 ...
- novnc安装教程
适配于centos7 1.安装vncserver # stop selinux and iptables setenforce systemctl stop firewalld systemctl d ...
- got positional argument after named arguments.原因
- Codeforces 835C - Star sky - [二维前缀和]
题目链接:http://codeforces.com/problemset/problem/835/C 题意: 在天空上划定一个直角坐标系,有 $n$ 颗星星,每颗星星都有坐标 $(x_i,y_i)$ ...
- pytorch定义一个简单的神经网络
刚学习pytorch,简单记录一下 """ test Funcition """ import torch from torch.autog ...
- [ovs] ovs开启日志debug
如题 [root@vrouter1 ~]# ovs-appctl vlog/set netdev:file:dbg [root@vrouter1 ~]# ovs-appctl vlog/set net ...
- 转:环绕通知返回值 object 类型
遇到 AOP 环绕通知报错 “return value from advice does not match primitive return type for: public boolean” 百 ...
- vue项目使用vue-photo-preview插件实现点击图片放大预览和移动
官方链接: http://npm.taobao.org/package/vue-photo-preview # 安装 npm install vue-photo-preview --save # 引入 ...
- PyCharm 常用习惯设置
1.pycharm改变选中行时改行的颜色和光标所在行的颜色 1.是光标所在行的背景颜色,写代码,每写到这一行,就会是这种颜色,所以尽量改成和你代码背景颜色相近的 2.应该是旁边行号所在背景颜色 3.是 ...
- swift一些常用系统方法的简化使用
//获取Image func FImage(_ imageName:String) -> UIImage { return UIImage(named:imageName)! } //获取Url ...