Problem 132
Longest Valid Parentheses
Hard · 30 pts · String, Stack, Dynamic Programming
Problem
You are given a string of '(' and ')' characters. Find the length of the longest substring (contiguous block) that is a valid, well-formed parentheses string. Print 0 if there is none. For example, in ")()())" the longest valid substring is "()()", of length 4. A stack of indices solves it in one pass: push the index of each '(', and on each ')' pop; if the stack becomes empty, push the current index as a new base, otherwise the valid length ending here is the current index minus the index on top of the stack.
Input
A single string of '(' and ')'.
Output
Print the length, or 0 if there is no valid substring.
Constraints
1 <= length <= 30000
Example input
(()
Example output
2
Explanation
In "(()", the first '(' is never closed, but the substring "()" formed by the last two characters is valid. So the longest valid length is 2.