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, and set all positions of unmatched parentheses to 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 becomesFind the length of the longest consecutive 0s
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
#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 0s                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;        }};
Loading comments…