Longest Valid Parentheses⚓︎
Description⚓︎
Given a string containing just the characters '('
and ')'
, return the length of the longest valid (well-formed) parentheses substring.
A substring is a contiguous non-empty sequence of characters within a string.
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
Constraints:
0 <= s.length <= 3 * 10^4
s[i]
is'('
, or')'
.
Solution⚓︎
Dynamic Programming⚓︎
- Time complexity: \(O(n)\);
- Space complexity: \(O(n)\).
Using Stack (Recommended)⚓︎
we start by pushing \(−1\) onto the stack. For every (
encountered, we push its index onto the stack.
For every )
encountered, we pop the topmost element. Then, the length of the currently encountered valid string of parentheses will be the difference between the current element's index and the top element of the stack.
If, while popping the element, the stack becomes empty, we will push the current element's index onto the stack. In this way, we can continue to calculate the length of the valid substrings and return the length of the longest valid string at the end.
See this example for a better understanding.
- Time complexity: \(O(n)\);
- Space complexity: \(O(n)\).
Greedy⚓︎
- Time complexity: \(O(n)\);
- Space complexity: \(O(1)\).