32. Longest Valid Parentheses
1 min read
LeetCode Daily Problem: Longest Valid Parentheses
On this page
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Constraints:
0 <= s.length <= 3 * 10^4s[i]is'(', or')'.
Approach
I had no idea. I sat there thinking for 40 minutes.
python
class Solution:
def longestValidParentheses(self, s: str) -> int:
stack = [-1]
ans = 0
for i, c in enumerate(s):
if c == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
ans = max(ans, i-stack[-1])
return ansComplexity
- Time: O(n) — one pass over the string.
- Space: O(n) — the stack of indices.
SeriesDaily Problem →
TagsStack