Given A string containing just the characters ‘(‘
‘)‘
and, find the length of the longest valid (well-formed) parenthe SES substring.
"(()"
for, the longest valid parentheses substring "()"
are, which has length = 2.
Another example ")()())"
is, where the longest valid parentheses substring "()()"
are, which has length = 4.
Question: Find the longest valid parenthesis substring.
Problem Solving Ideas:
The first time to do, thought is to ask for the entire string of effective parenthesis length is how much, think of a stack can be used to find, thought seems pretty simple. Throw to the Leetcode ran a bit, the result is wrong, only the original is to seek continuous maximum effective bracket length.
After re-understanding test instructions, start doing the second time.
Imagine the parentheses match, just like playing the "Everyday Love elimination" New game, the next two characters, the left is ' (', the right is ') ', then the match succeeds, the matching successful character is replaced with '. '.
With up to N/2 times, you can replace all valid brackets in S with '. ' and then count the number of consecutive '. ', which is the solution of the problem, time-consuming O (n*n). Realize, throw to Leetcode above, incredibly passed, is slow some.
There is no faster way to think about it, Lenovo to the first use of the stack, you can use the stack one traversal to replace all valid parentheses with '. '.
The first step: a traversal, the stack only holds ' (' subscript.
When found a ' (', then pressed into the stack;
When a ') ' is found, replace the Stack.top's character with '. ' and Eject Stack.pop (). Time-consuming O (n).
Step two: Find the longest length of continuous '. ', time-consuming O (n).
1stack<int>SK;2 3 for(inti =0; I < s.size (); i++) {4 if(S[i] = =')') {5 if(Sk.empty ()) {6 Continue;7}Else{8 intIDX =sk.top ();9 Sk.pop ();TenS[IDX] =marked; OneS[i] =marked; A } -}Else{ - //S[i] is ' (' the - Sk.push (i); - } - } + - + intLen =0; A intMaxL =0; at for(inti =0; I < s.size (); i++) { - if(S[i] = ='.') { -len++; -}Else{ -MaxL =Max (MaxL, Len); -Len =0; in } - } toMaxL =Max (MaxL, Len); + - returnMaxL;
[Leetcode] Longest Valid parentheses problem solving thought