Cover image for LeetCode Hot 100 P32 Longest Valid Parentheses

LeetCode Hot 100 P32 Longest Valid Parentheses


Timeline

Timeline

2026-03-21

init

Dynamic Programming, Stack

Problem:

  • Simulate with a stack, mark all positions of unmatched parentheses as 1,
    • For example:()(()the mark is [0, 0, 1, 0, 0]
    • Another example:)()((())the mark is [1, 0, 0, 1, 0, 0, 0, 0]
  • After such processing, this problem becomesfinding the length of the longest consecutive zeros
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <string>
#include <vector>
#include <stack>

using std::string;
using std::vector;
using std::stack;

class Solution {
public:
int longestValidParentheses(string s)
{
int i, j, n = s.size();
int max_len = 0;
stack<int> stk;
vector<int> arr(n, 0);

for (i = 0; i < n; i++) {
if (s[i] == '(') {
stk.push(i);
} else {
if (stk.empty())
arr[i] = 1;
else
stk.pop();
}
}
while (!stk.empty()) { //unmatched parentheses
arr[stk.top()] = 1;
stk.pop();
}
// Find the longest consecutive zeros
i = 0;
while (i < n) {
if (arr[i] == 0) {
j = i;

while (j < n && arr[j] == 0)
j++;

max_len = std::max(max_len, j - i);
i = j + 1;
} else {
i++;
}
}

return max_len;
}
};