32. 最长有效括号
问题描述
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
方法1:栈
class Solution:
def longestValidParentheses(self, s: str) -> int:
# 栈
lenth = len(s)
stack = [-1]
res = 0
for i in range(lenth):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
res = max(res, i - stack[-1])
return res
方法2:贪心一点
class Solution:
def longestValidParentheses(self, s: str) -> int:
#贪心一点,左-->右,右-->左
lenth = len(s)
res = 0
# 左--> 右
left = right = 0
for val in s:
if val == '(':
left += 1
else:
right += 1
if left == right:
res = max(res, 2 * left)
elif right > left:
left = right = 0
# 右-->左
left = right = 0
for i in range(lenth - 1, -1, -1):
if s[i] == ')':
right += 1
else:
left += 1
if left == right:
res = max(res, 2 * left)
elif left > right:
left = right = 0
return res