Skip to content

Instantly share code, notes, and snippets.

@shanecandoit
Created June 12, 2024 15:32
Show Gist options
  • Save shanecandoit/a732518a0eaa75423389e59431e68adc to your computer and use it in GitHub Desktop.
Save shanecandoit/a732518a0eaa75423389e59431e68adc to your computer and use it in GitHub Desktop.
longest valid parens using a stack
"""
32. Longest Valid Parentheses
Hard
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses
substring
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = ""
Output: 0
"""
class Solution:
def longestValidParentheses(self, s: str) -> int:
stack = [-1]
max_len = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if len(stack) == 0:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_len
assert Solution().longestValidParentheses("(()") == 2
assert Solution().longestValidParentheses(")()())") == 4
assert Solution().longestValidParentheses("") == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment