class Solution: def longestValidParentheses(self, s: str) -> int: """ note that every index in stack is offset to the left by one, to make finding the length between two indices easier. (normally you'd have to do r - l + 1, but in our case, l is already l-1). """ # we initialize with -1 for the case where the # valid substring starts at the beginning of s stack = [-1] ans = 0 # stack stores the index BEFORE where # a valid substring could start for i in range(len(s)): if s[i] == "(": stack.append(i) else: stack.pop() if not stack: stack.append(i) else: ans = max(ans, i - stack[-1]) return ans