Question

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

For “(()”, the longest valid parentheses substring is “()”, which has length = 2.

Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.

Hide Tags Dynamic Programming String
Hide Similar Problems (E) Valid Parentheses


Solution 1

time complexity: O(n), traverse one time
space complexity: at most O(n)

get idea from here.

the great one

class Solution(object):def longestValidParentheses(self, s):""":type s: str:rtype: int"""stack = []maxnum, start = 0, 0          # start records the start ind of this sequencefor ind,elem in enumerate(s):if elem=="(":stack.append(ind)else:# elem==')'if stack!=[]:stack.pop()if stack==[]:maxnum = max( maxnum, ind-start+1)else:maxnum = max( maxnum, ind-stack[-1])else:                         start = ind + 1   # the sequence is broken, start it againreturn maxnum

Solution 2

Using dynamic programming
time complexity: O(n), space complexity: O(n)

This idea is from here. He uses one list in which res[i] records the number of longest sequence with the last elem s[i-1]. However he didn’t notice there is only one valid longest sequence before any elem since we have merged all possible consecutive sequence once. The simpler solution is at here.

Code

class Solution(object):def longestValidParentheses(self, s):""":type s: str:rtype: int"""res = [0]*(len(s)+1)  # res[i] records the longest sequence with the last elem i maxnum = 0for i in range(1,len(s)+1):j = (i-1) - res[i-1] - 1   # find the previous valid available indexif s[i-1]=="(" or j<0 or s[j]==')':res[i] = 0else:# the longest number before j (last elem of res[j] is s[j-1]) + s[j] + dp[i-1] + s[i-1]res[i] = res[j] + 1 + res[i-1] + 1  maxnum = max( maxnum, res[i])return maxnum

For dynamic programming, we can give different meaning to list according to our algorithm. In this problem, I thought of one way to make s[i] be the number of longest sequence before s[i-1], but have no result. The smart way is to make it be the number with the last elem s[i-1]


Solution 3

time complexity: O(n) , traverse two times
space complextiy: O(1),
get idea from here.

class Solution(object):def longestValidParentheses(self, s):""":type s: str:rtype: int"""maxnum ,cur, start = 0, 0, -1for ind,elem in enumerate(s):if elem=='(':cur += 1else:cur -= 1if cur<0:start, cur = ind, 0elif cur==0:maxnum = max( maxnum, ind-start )s = list(s)s = "".join(reversed(s))cur, start = 0, -1for ind,elem in enumerate(s):if elem==')':cur += 1else:cur -= 1if cur<0:start, cur = ind, 0elif cur==0:maxnum = max( maxnum, ind-start)return maxnum       

It is easy to get the first part of the code above. However, it can’t work for the case “()(()”. I stunk on it for a long time. A cleverer way is to do the same thing in a reversed order. Why ? ‘(’ and ‘)’ are symmetry.

Leetcode: Longest Valid Parentheses相关推荐

  1. LeetCode Longest Valid Parentheses

    原题链接在这里:https://leetcode.com/problems/longest-valid-parentheses/ 题目: Given a string containing just ...

  2. 最长有效括号子串长度 c语言,LeetCode: Longest Valid Parentheses (求最长有效匹配括号子串的长度)...

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

  3. [Leetcode] Longest Valid Parentheses

    找出字串裡最長的合法括號組 簡單說,一樣stack搜尋合法parenth,把不合法的 ( & ) index 紀錄下來,最後算index間的差值取最大就是最長的 public class So ...

  4. LeetCode 32. Longest Valid Parentheses

    问题链接 LeetCode 32. Longest Valid Parentheses 题目解析 给出只包含左右括号的字符串,返回最长的括号匹配字符串长度. 解题思路 括号匹配问题一般借助 栈,便于理 ...

  5. LeetCode算法入门- Longest Valid Parentheses -day12

    LeetCode算法入门- Longest Valid Parentheses -day12 Given a string containing just the characters '(' and ...

  6. Longest Valid Parentheses leetcode java

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

  7. LeetCode: 20. Valid Parentheses

    0509第1题(虽然是08做的,但这会已经09了) 题目 Given a string containing just the characters '(', ')', '{', '}', '[' a ...

  8. [LeetCode]--20. Valid Parentheses

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

  9. LeetCode之Valid Parentheses

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

最新文章

  1. Class.forName( )你搞懂了吗?——转
  2. 学习ASP.NET Core Razor 编程系列九——增加查询功能
  3. python脚本实例手机端-python链接手机用Python实现命令行闹钟脚本实例
  4. 如何使用 dotTrace 来诊断 netcore 应用的性能问题
  5. 机器学习常用模型:决策树_fairmodels:让我们与有偏见的机器学习模型作斗争
  6. shishuo-CMS-master
  7. Vue服务端配置示例
  8. jquerymobile 基础教程
  9. Struts提供我们方便地将客户端上传的文件处理
  10. 上班时真的很困怎么办
  11. putty怎么进入文件夹_如何安装及使用PuTTY
  12. 判断是否为IE浏览器
  13. 互联网快讯:天猫双11总交易额再创新高;极米投影产品成双十一单品爆款;柔宇科技斩获6亿元大额订单
  14. Qt编写可视化大屏电子看板系统5-恢复布局
  15. 清华学堂东侧木质结构焚毁心痛不已
  16. c语言把结构体首地址放入指针,C语言基础———指针,结构体指针,函数指针
  17. 段正淳是否是一个卑劣的人?
  18. 前端开发者的现代 C++ 课:JavaScript 与 C++ 的差异
  19. 字符转ASCII码,ASCII码转字符
  20. LibreOffice Draw vs. 微软Office Visio

热门文章

  1. JSP基础:(7)jsp分页与文件上传下载
  2. 计算机毕设Python+Vue医院人事及科室病区管理(程序+LW+部署)
  3. Python-求一元二次方程ax^2+bx+c=0的解
  4. 百度接口根据关键字生成文章
  5. 成功解决ValueError: pos_label=1 is not a valid label: array([‘0‘, ‘1‘], dtype=‘<U1‘)
  6. 鼓式制动系统行业研究及十四五规划分析报告
  7. Redis安装及集群部署
  8. springboot系列课程笔记-第一章-Spring Boot入门
  9. Python入门学习笔记——12.文件操作
  10. Questa CDC(安全性测试)