Length of longest valid substring
Given an input string consisting of opening and closing parenthesis find the length of the longest valid contiguous subexpression
An example is worth a thousand words:
input: "()"
output: 2
input: ")())())"
output: 2
input: ")(()())("
output: 6
This problem exhibits similarities with the the maximum subarray problem although it does require a history to check for the continuation of the current valid subexpression. A stack is the natural data structure to be used to track the previous expression openings. The breakpoint of a contiguous subexpression is a closing parenthesis )
with no pending (
on the stack.
The algorithm is quite simple and runs in \( O(N) \)