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.
Solution: With stack, complexity O (n)
PackageLeetcode2;ImportJava.util.Stack; Public classlongestvalid_parentheses { Public Static intLONGEST_VP_DP (String s) {Stack<Integer> re =NewStack<integer>(); intStart=-1; intMaxl=0; intLocation ; for(intI=0;i<s.length (); i++){ if(S.charat (i) = = ' (') {Re.push (i); }Else{ if(Re.empty ()) {Start=i; }Else{ Location=Re.pop (); if(Re.empty ()) {Maxl=math.max (Maxl, I-start);//no perimeter (parentheses, to I have got a local maximum value}Else{Maxl=math.max (Maxl, Re.peek ()-i);//the perimeter is still there (, no end! } } } } returnMaxl; } Public Static voidMain (string[] args) {//TODO auto-generated Method StubString string= "() () ("; System.out.println (LONGEST_VP_DP (string)); }}
Leetcode32. Longest Valid parentheses