32. Longest Valid Parentheses
Problem description:
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
1 | Input: s = "(()" |
Example 2:
1 | Input: s = ")()())" |
Example 3:
1 | Input: s = "" |
Constraints:
0 <= s.length <= 3 * 104
s[i]
is'('
, or')'
.
Solution:
- Only need length of valid, so dp might be better
- Calculate length when find a
)
ats[i]
, and there’re two subcasess[i-1] = (
, it could form a valid withs[i]
s[i-1] = )
, we need to find previous not used(
.
1 | class Solution: |
time complexity: $O(n)$
space complexity: $O(n)$
reference:
https://leetcode.com/problems/longest-valid-parentheses/discuss/14141/Pure-1D-DP-without-using-stack-(python)-with-detailed-explanation/14533
https://leetcode.com/problems/longest-valid-parentheses/discuss/14284/8-line-Python-solution-stack-80ms
https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode-solution/
related problem: