Problem
Given a string containing just the characters'(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Examples
Constraints
- 0 <= s.length <= 3 * 10^4
s[i]is'(', or')'.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 32 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 32 # by problem number
lcpy gen -s longest_valid_parentheses # by problem name
'(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Input: s = ""
Output: 0
s[i] is '(', or ')'.class Solution:
# Time: O(n)
# Space: O(n)
def longest_valid_parentheses(self, s: str) -> int:
max_length = 0
# Stack of indices; seeded with -1 as the last "unmatched" position
stack: list[int] = [-1]
for i, char in enumerate(s):
if char == "(":
stack.append(i)
else:
stack.pop()
if not stack:
# Unmatched ')', reset the base index
stack.append(i)
else:
max_length = max(max_length, i - stack[-1])
return max_length
| Time | Space |
|---|---|
| O(n) | O(n) |