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 is " () ", which has length = 2.
Another example ")()())" is, where the longest valid parentheses substring "()()" are, which has length = 4.
Test instructions: Given a string containing parentheses, find a valid word-length brace string. Can be matched in sequence. This problem has just begun to think for a long time ~ ~, with a stack to do the problem, it is easy to find all valid parentheses in the string length. But how do we find effective substrings? If we can find the index of the invalid parenthesis, subtract the valid index from the last invalid index, then it is the valid substring of the character. It is also easy to find the most effective string for this to be understood.
public int longestvalidparentheses (String s) { if (s==null) return 0; int len=s.length (); int i=0; Stack<integer> stack=new stack<integer> (); char ch; int res=0; while (I<len) { Ch=s.charat (i); if (ch== ' (') stack.push (i);//We change the thinking, the index of the brackets into the stack else { if (!stack.isempty () && S.charat (Stack.peek ()) = = ' (')//If ') ', and when matched with stack top bracket, pops { stack.pop (); Res=math.max (Stack.isempty () I+1:i-stack.peek (), res);//null, proof that there is no invalid parenthesis in front, will be i+1; not empty, preceded by an invalid character, minus the invalid character's index } else { Stack.push (i); } } i++; } return res; }
[Java] LeetCode32 longest Valid parentheses