【leetcode刷题】32. Longest Valid Parentheses
原题链接
https://leetcode.com/problems/longest-valid-parentheses/
解题思路
利用动态规划。如果遍历过程中出现了一个),则检查它的前面是否为(,如果是,就给这个后括号处对应的长度值加2,;继续遍历,如果接着还是),则再往前检索一位,…代码
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
if s == '':
return 0
result = [0 for i in range(0,len(s))]
for right in range(1, len(s)):
if s[right] == ')':
left = right - 1 - result[right-1]
if s[left] == '(' and left>=0:
result[right] = result[right-1] + 2
if left-1>=0:
result[right] += result[left-1]
return max(result)
参考
https://blog.****.net/qqxx6661/article/details/77876647
https://shenjie1993.gitbooks.io/leetcode-python/032 Longest Valid Parentheses.html