# 先通过栈找到能够匹配的括号,再排序,最后找出升序中连续的最大长度
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
res = []
stack = []
l = len(s)
for i in range(l):
if s[i] == '(':
stack.append(i)
if s[i] == ")" and stack:
res.append(stack.pop())
res.append(i)
res.sort()
n_res = len(res)
if not n_res:
return 0
else:
ans = 0
left = 0
right = 0
while right < n_res-1:
if res[right+1] == res[right] +1:
right += 1
else:
ans = max(ans, right - left + 1)
right += 1
left = right
ans = max(ans, right-left+1)
return ans
32. 最长有效括号
最新推荐文章于 2024-10-30 13:16:11 发布