Title: Enter a string containing only parentheses to find the length of the longest legal bracket substring
Like what:
"(()"--"2, the longest valid substring is" () "
") () () ())"--"4, the longest valid substring is" () () "
Problem Solving Ideas:
If the input is the left parenthesis directly into the stack, if it is the right parenthesis, if the stack is empty or the stack at this time is not open parenthesis at the same time the record effective length of the temporary variable is set to 0, if the top of the stack is the left parenthesis stack and the record length of the temporary variable is added 2.
Code:
Import Java.util.stack;public class Leetcode_longestvalidtokens {/** * @param args */public static void main (string[] args ) {//TODO auto-generated method stubstring input= ") ()) ())"; SYSTEM.OUT.PRINTLN (Longestvalidtokens (input));} public static int longestvalidtokens (String input) {char[] Inputarray=input.tochararray (); int length= Inputarray.length;if (length==0) return 0;int validlength=0;int maxvalidlength=0; Stack<character> stack=new stack<> (); for (int i=0;i<length;i++) {if (inputarray[i]== ') ') {if ( Stack.isempty ()) {validlength=0;} else {char temppeek=stack.peek (); if (temppeek== ' (') {stack.pop (); Validlength=validlength+2;maxvalidlength=math.max (Maxvalidlength, validlength);} else {validlength=0;}}} else {Stack.push (inputarray[i]);}} return maxvalidlength;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Maximum valid brace length Java