Java Stack class solves the issue of matching parentheses
The java. util package provides the stack class, which can be used to solve many problems, such as the typical matching of brackets.
First, let's look at the stack class.
Method
Example:
Description: There is a sequence of parentheses. Check whether the parentheses match. Enter N (N 0-100) In the first line, indicating that N groups of test data exist. The next N rows Input Multiple groups of input data. Each group of input data is a string of S (the length of S is less than 10000, and S is not an empty string), and the number of test data groups is less than five. Data guarantee S only contains "[", "]", "(", ")" and outputs each group of input data to occupy one row, if the parentheses contained in the string are paired, Yes is output. If not paired, No is output. Input 3 [(]) ([[] ()]) sample output NoNoYes
Ideas:
Apply pressure to the stack when matching the left brackets.
Matching to the right parenthesis is compared with the top element of the stack. If matching a pair, the stack is output. Otherwise, No is returned and the judgment is ended.
Stack null has not been matched, and No is returned. End judgment
Package com. day1; import java. util. imports; import java. util. stack; public class Main {public static void main (String [] args) {custom input = new partition (System. in); int n = input. nextInt (); String [] arr = new String [n]; for (int I = 0; I <arr. length; I ++) {arr [I] = input. next () ;}for (String string: arr) {System. out. println (isMatch (string);} private static String isMatch (String str) {Stack
Stack = new Stack <> (); // create a stack/*** scan strings one by one * encounter left parentheses into the Stack, in case of right brackets, the system determines */for (int I = 0; I <str. length (); I ++) {if (str. charAt (I )! = ')' & Str. charAt (I )! = ']') {Stack. push (str. charAt (I);} else {// if the stack is empty or does not match, No if (stack. empty () |! IsBracketMatch (stack. peek (), str. charAt (I) {return "No";} else {stack. pop () ;}} return "Yes ";} /*** determine whether two parentheses match * @ param c1 * @ param c2 * @ return */private static boolean isBracketMatch (Character c1, Character c2) {if (c1 = '(' & c2 = ') {return true;} if (c1 =' ['& c2 ='] ') {return true;} return false ;}}