Problem
Find the longest valid substring.
Algorithm
Use a stack to find matching parenthes and combinate the sustring during the process. The value save in the stack is the valid substring.
Code
class Solution:
def longestValidParentheses(self, s: str) -> int:
sSize = len(s)
ans = 0
index = 0
while index < sSize:
stack = []
susum = 0
while index < sSize:
if s[index] == '(':
stack.append(0)
elif stack:
subsum = stack.pop()
if stack:
top = stack.pop() + subsum + 2
if ans < top:
ans = top
stack.append(top)
else:
susum += subsum + 2
else:
break
index += 1
index += 1
if ans < susum:
ans = susum
return ans