https://leetcode.com/problems/longest-valid-parentheses/
Longest Valid parentheses
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.
No use of dynamic planning, the use of a stack ...
Raise a chestnut:) (() (() () () (
The number in the stack is weight, and when you pour it down with a stack, it becomes a sequence.
It's like this.-1 2 10 8 2-1 12 8-1 2 4
The problem is converted into a positive number in the combined sequence, the biggest being the result.
Ah ah ah, this solution good trouble, wrote a lot of lines, good sad, honest dp is good.
1 /**2 * @param {string} s3 * @return {number}4 */5 varLongestvalidparentheses =function(s) {6 varstack = [];7 for(vari = 0; i < s.length; i++){8 if(S[i] = = = ' ('){9 Stack.push ({TenValue: ' (', OneWeight:-1 A }); -}Else{ - varTargetindex =-1; the for(varj = stack.length-1; J >= 0; j--){ - if(Stack[j].value = = = ' ('){ -Targetindex =J; - Break; + } - } + A if(Targetindex = = =-1){ at Stack.push ({ -Value: ') ', -Weight:-1 - }); -}Else{ - varMerge =NULL; in while(stack.length-targetindex-1){ - varTMP =Stack.pop (); to if(Merge = = =NULL){ +Merge =tmp; -}Else{ theMerge.value + =Tmp.value; *Merge.weight + =Tmp.weight; $ }Panax Notoginseng } - Stack.pop (); the if(Merge = = =NULL){ + Stack.push ({ AValue: ' () ', theWeight:2 + }); -}Else{ $ Stack.push ({ $Value: "(" + Merge.value + ")", -Weight:merge.weight + 2 - }); the } - }Wuyi } the } - Wu varMax = 0; - varCurrmax = 0; About for(i = 0; i < stack.length; i++){ $ varCurr =Stack[i]; - if(Curr.weight = = =-1){ - if(Currmax >max) { -Max =Currmax; A } +Currmax = 0; the}Else{ -Currmax + =Curr.weight; $ } the } the if(Currmax >max) { theMax =Currmax; the } - returnMax; in};
[Leetcode] [JavaScript] Longest Valid parentheses