Whether the Java implementation brackets match (given a string of strings to see whether the brackets appear in pairs)

It can be said that it's an algorithm problem. Use stack to solve... The basic ideas are as follows
1. Traversing each character of a string
 2. If left parenthesis is found, the character is pushed into the stack
 3. If it is a right bracket, first go to the top of the stack to find the corresponding value
 4. If the stack is empty, false will be returned. If it is matched, pop the left bracket. If it is not matched, false will be returned
 5. Finally, see whether the brackets in the storage stack match. That is, if the stack is empty at last, return true, otherwise return false

Here is the code part of the implementation

package Algro;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class Match {

    static  boolean isMatch(String s){
        //Define the correspondence between left and right brackets
        Map<Character,Character> bracket  = new HashMap<>();

        Stack stack = new Stack();

        for(int i = 0; i < s.length(); i++){

            Character temp = s.charAt(i);//Convert to character first
            //Left bracket or not

                //Right bracket or not
            }else if(bracket.containsKey(temp)){
                    return false;
                //If left and right brackets match
                if(stack.peek() == bracket.get(temp)){
                    return false;

        return stack.isEmpty()? true: false;


    public static void main(String[] args) {

        System.out.println(isMatch("(***)-[{-------}]")); //true
        System.out.println(isMatch("(2+4)*a[5]")); //true
        System.out.println(isMatch("({}[]]])")); //false
        System.out.println(isMatch("())))")); //false


Reference articles

The use of various data structures still needs more practice, otherwise the interview will always be confused

Tags: Java

Posted on Sun, 05 Jan 2020 14:07:31 -0800 by poltort