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. Spark Pipeline

    一个简单的Pipeline,用作estimator.Pipeline由有序列的stages组成,每个stage是一个Estimator或者一个Transformer. 当Pipeline调用fit,s ...

  2. B - Space Ant

    The most exciting space discovery occurred at the end of the 20th century. In 1999, scientists trace ...

  3. 学习mongoDB的网站

  4. shell脚本的基本结构以及如何执行

    1.shell脚本通常以.sh为后缀,不是说不带这个.sh脚本就不会执行,而是大家一种通用的命名规范而已 2.shell脚本中的第一行一定是:#! /bin/bash.该命令说明,该文件使用的是bas ...

  5. 深度学习中将类别标签映射到one_hot向量

    有时我们的样本标签,都是标记从0开始直至到类别的个数.在模型训练的时候,这些标签需要变成one_hot向量,这样才能够跟softmax出来的概率做互熵损失,计算loss. 那么,映射的方法如下: de ...

  6. 【瞎搞题】gym226123 L. For the Honest Election

    http://codeforces.com/gym/226123/problem/L 题解:手摸几组数据,发现一个规律:将n 质因数分解,答案就是 每个质因数/2+1后再乘起来. 然后考虑2的情况: ...

  7. deepin中idea中文乱码解决

    打开终端 命令: sudo su 输入密码: aptitude search uming 显示: root@terwer-PC:/home/terwer# aptitude search uming ...

  8. Flink – Stream Task执行过程

    Task.run if (invokable instanceof StatefulTask) { StatefulTask op = (StatefulTask) invokable; op.set ...

  9. oracle基本命令笔记

    最近由于工作原因,再次接触oracle,因此重新来熟知下oracle基本的命令. --改密码 1.运行——键入“cmd” 回车2.键入“sqlplus/nolog” 回车3.键入“conn/as sy ...

  10. delphi连接mysql (通过libmysql.dll连接)

    首先在窗体上拖拽sqlconnection和sqlquery两个控件: 然后在测试连接中,写入以下代码(注意exe生成目录下需要有dbxopenmysql50.dll和libmysql.dll) SQ ...