Given a string containing just the characters'('and')', find the length of the longest valid (well-formed) parentheses substring.
For"(()", the longest valid parentheses substring is"()", which has length = 2.
Another example is")()())", where the longest valid parentheses substring is"()()", which has length = 4.
The Idea: First I create a vector that that iterates through the original string s and counts the relative number of matching parenthesis. For example:
Parentheses that are known to be impossibly matched are set to -1 (shown as x). This is identified when the current number of ')' exceeds '('. Using this array, a properly matched paranthesis could then be identified in the array as a n to the first n-1 pair. Starting from the beginning of the string and iterating towards the right, we are able to identify the longest n to n-1 pair. However, it may follow that there another set of valid paranthesis right after the previous matching pair, and if so - this too must be included in the maximum length. So to do this, I simply go through the operation of finding all the longest n to n-1 pairs that follow one another. In the end I get something along the lines of:
+---------+ +--+ ++ +-------+--------+---+-+
This gives us a set of non overlapping intervals to work with. I then merge continuous intervals (intervals where the the i+1th interval end connects with ith interval start). Finally, I iterate through these interval to return the largest width.
Complexity: O(n^2) time O(n) space. The worst case can be identified with the string s = "((((((((((((((((..." since get_first_valid_match tries to anticipate a match with proceeding (.
The Idea: The approach this time around is very similar with the previous. The main difference is that now to collect the valid intervals a stack is used. A valid interval is found the moment s[i] = ')' and the stack is not empty. After collecting these intervals, we sort by their start time. This ensures that when we merge the intervals next, continuous intervals will be lined up nicely for the merge.
)(())))(())())
( )
()
( )
()
()
Overlapping intervals can get ignored with a simple check (their end time is within the range of the previous end time).
Complexity:O(N + NlogN + N + N) for stack ops, sorting, merging, and find max, respectfully. O(N)space.