leetcode 32 最长有效括号

给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。

示例 1:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:

输入: ")()())"
输出: 4
解释: 最长有效括号子串为 “()()”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class (object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = [0]
lmax = 0
if not s:
return 0
for i in s:
if i == '(':
stack.append(0)
else:
if len(stack) <=1:
stack = [0]
else:
stack[-2] += stack[-1]+2
stack.pop()
lmax = max(lmax, stack[-1])
return lmax