一开始使用dfs 贡献了一发tl 后面发现这题的解法很巧妙 算法还是美妙的
上代码:
class Solution:
def longestValidParentheses(self, s: str) -> int:
sList = list(s)
sLen = len(s)
maxSum = 0
newList = []
last = -1
for i in range(sLen):
if sList[i] == '(':
newList.append(i)
else:
if newList == []:
last = i
else:
newList.pop()
if newList == []:
maxSum = max(maxSum, i - last)
else:
maxSum = max(maxSum, i - newList[len(newList) - 1])
return maxSum