Longest Valid Parentheses — JavaScript Coding Problem
Difficulty: hard | Category: stack
Problem Description
Given a string containing just the characters `'('` and `')'`, return the length of the longest valid (well-formed) parentheses substring. Hint: Use a stack. Push indices of unmatched `'('`. When you see `')'`, pop from the stack — if empty, push the current index as the new base; otherwise, the current valid length is `i - stack.top()`.
Examples
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