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(最长有效括弧)的更多相关文章

  1. leetcode第31题--Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  2. [LeetCode] Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  3. [Leetcode] longest valid parentheses 最长的有效括号

    Given a string containing just the characters'('and')', find the length of the longest valid (well-f ...

  4. [LeetCode] 32. Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  5. leetcode解题报告 32. Longest Valid Parentheses 用stack的解法

    第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...

  6. LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]

    题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...

  7. [leetcode]32. Longest Valid Parentheses最长合法括号子串

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  8. LeetCode (32) Longest Valid Parentheses

    题目 Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...

  9. 【LeetCode每天一题】Valid Parentheses(有效的括弧)

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  10. leetcode解题报告 32. Longest Valid Parentheses 动态规划DP解

    dp[i]表示以s[i]结尾的完全匹配的最大字符串的长度. dp[] = ; ; 开始递推 s[i] = ')' 的情况 先想到了两种情况: 1.s[i-1] = '(' 相邻匹配 这种情况下,dp ...

随机推荐

  1. Linux Kafka集群管理工具kafka-manager的安装使用

    一.kafka-manager简介 kafka-manager是目前最受欢迎的kafka集群管理工具,最早由雅虎开源,用户可以在Web界面执行一些简单的集群管理操作.具体支持以下内容: 管理多个集群 ...

  2. Django中,ajax检测注册用户信息是否可用?

    ajax检测注册用户信息主体思路 1.在settings.py中配置需要使用的信息 #对static文件进行配置 STATICFILES_DIRS=[ os.path.join(BASE_DIR,'s ...

  3. 具有键“XXX”的 ViewData 项属于类型“System.Int32”,但它必须属于类型“IEnumerable<SelectListItem>

    原因是Edit视图中有@Html.DropDownListFor(m => m.BirthdayAD... 但是没有从Controller中没有设置值

  4. .NET Core 中依赖注入 AutoMapper 小记

    最近在 review 代码时发现同事没有像其他项目那样使用 AutoMapper.Mapper.Initialize() 静态方法配置映射,而是使用了依赖注入 IMapper 接口的方式 servic ...

  5. 一篇采访窥C#的未来

    今天坐公交时用手机打开 .NET Blog 阅读这周的 The week in .NET ,在看 Virtual Panel: What's Next for .NET? 这篇采访报道时,被其中对 R ...

  6. TensorRT优化过程中的dropout问题

    使用tensorRT之前,你一定要注意你的网络结构是否能够得到trt的支持,无论是CNN还是RNN都会有trt的操作. 例如:tf.nn.dropout(features, keep_prob),tr ...

  7. sklearn的K折交叉验证函数KFold使用

    K折交叉验证时使用: KFold(n_split, shuffle, random_state) 参数:n_split:要划分的折数 shuffle: 每次都进行shuffle,测试集中折数的总和就是 ...

  8. React组件中的key

    React组件中的key 一.key的作用 react中的key属性,它是一个特殊的属性,它是出现不是给开发者用的(例如你为一个组件设置key之后不能获取组件的这个key props),而是给reac ...

  9. Hadoop开发环境配置2-eclipse集成maven插件

    1.下载eclipse:eclipse-SDK-4.5-win32-x86_64.zip 下载地址: http://archive.eclipse.org/eclipse/downloads/drop ...

  10. Zabbix unreachable poller processes more than 75% busy

    “Zabbix poller processes more than 75% busy”警报问题解决 虽然Zabbix的监控警报各种有,碰到最多的几个莫过于内存耗尽,网络不通,IO太慢还有这个“Zab ...