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.
This is the longest effective parenthesis than the previous Valid parentheses to verify the parentheses more difficult, here we still use the stack to solve, we need to define a start variable to record the starting position of the legal bracket string, we traverse the string, if we encounter an opening parenthesis, the current subscript is pressed into the stack, If a closing parenthesis is encountered, if the current stack is empty, the next coordinate position is recorded to start, and if the stack is not empty, the top element of the stack is taken out, and if the stack is empty, the result is updated and the larger value in I-start + 1 is updated, otherwise the result and the large values in the I-stack top element are as follows
classSolution { Public: intLongestvalidparentheses (strings) {intres =0, start =0; Stack<int>m; for(inti =0; I < s.size (); ++i) {if(S[i] = ='(') M.push (i); Else if(S[i] = =')') { if(M.empty ()) start = i +1; Else{m.pop (); Res= M.empty ()? Max (res, I-start +1): Max (res, I-m.top ()); } } } returnRes; }};
There is also a method of dynamic programming programming, which can be found in the blog of user's favorite brush.
[Leetcode] Longest Valid parentheses maximum effective bracket