Maximum valid brace length Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.