"032-longest Valid parentheses (maximum effective bracket)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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.
Main Topic
Given a string that contains only the parentheses number, the maximum number of valid parentheses is obtained.
Thinking of solving problems
Using stacks to implement
Code Implementation
Algorithm implementation class
ImportJava.Util.Deque;ImportJava.Util.LinkedList;ImportJava.Util.Stack; PublicClass Solution { Publicint longestvalidparentheses (Strings) {//To record the position of the opening and closing brackets to be matched Stack<Integer>St= New Stack<>(); IntMax = 0; for (int i= 0; I<S.Length (); I++) {//If the current character is a closing parenthesis, and the record stack is non-empty, and the previous character is an opening parenthesis if(s.CharAt (i)== ' ) ' && !St.IsEmpty ()&&S.CharAt (St.Peek ())== ' (') {///left bracket out stackSt.Pop ();//Seek maximum value Max =Math.Max(Max+ N-(St.IsEmpty ())? -1: St.Peek ())); }//In other cases, put characters into the stack Else{St.push (i); } }return Max; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47064939"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "032-longest Valid parentheses (maximum effective bracket)"