[LeetCode-interview algorithm classic-Java implementation] [032-Longest Valid Parentheses (maximum Valid brackets)],-javaparentheses
[032-Longest Valid Parentheses (maximum Valid brackets )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a string containing just the characters'('And')', Find the length of the longest valid (well-formed) parentheses substring.
For"(()", The longest valid parentheses substring is"()", Which has length = 2.
Another example is")()())", Where the longest valid parentheses substring is"()()", Which has length = 4.
Theme
Given a string that contains only parentheses, evaluate the maximum number of valid parentheses.
Solutions
Stack implementation
Code Implementation
Algorithm Implementation class
Import java. util. deque; import java. util. using list; import java. util. stack; public class Solution {public int longestValidParentheses (String s) {// used to record the Left and Right brackets to be matched. Stack <Integer> st = new Stack <> (); int max = 0; for (int I = 0; I <s. length (); I ++) {// if the current character is a right brace and the record stack is not empty, and the first character is a left brace if (s. charAt (I) = ')'&&! St. isEmpty () & s. charAt (st. peek () = '(') {// The left bracket of the stack st. pop (); // calculate the maximum value max = Math. max (max, I-(st. isEmpty ())? -1: st. peek ();} // in other cases, import the character into the stack else {st. push (I) ;}} return max ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47064939]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.