Bracket matching detection problem

Original title description:
Suppose an arithmetic expression can contain three kinds of parentheses: parentheses "(" and ")", square brackets "[" and "]" and curly brackets "{" and "}", and these three kinds of parentheses can be arbitrarily The order of nesting is used (eg: …[…{…}…[…]…]…[…]…(…)…). Write an algorithm that determines whether parentheses contained in a given expression are correctly paired (known expressions are stored in a sequence table whose data elements are characters).

answer:
This question belongs to the application of the stack, making full use of the stack's push and pop functions.

1. My answer
   After querying the ASCII code, }]) is 1 or 2 different from {[(, and there are only these six symbols in the expression, so the discriminant condition is written in this form, but this is not a good solution.
import java.util.Scanner;
import java.util.Stack;


public class parenthesis_matching {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Stack<Character> a = new Stack<>();
		int n = sc.nextInt();
		String s = sc.next();
		boolean flag = true;
		for(int i = 0;i < n;++i) {
			char c = s.charAt(i);
			if(c == '(' ||c == '{' ||c == '[' ) {
				a.push(c);
			}
			else {
				char m = a.peek();
				if(c == m + 1 || c == m + 2) {
					a.pop();
				}	
				else {
					System.out.println("false");
					flag = false;
					break;
				}
			}
		}
		if (flag == true) {
			if (a.isEmpty())
				System.out.println("true");
			else {
				System.out.println("false");
			}
		}
	}	
}

2. Someone else's answer
    Knowledge points to learn:
    a. I always wanted to write the sc.hasNext() method before, but unfortunately the general adjustment was wrong, so I used the method of inputting the numbers first, and then using the loop method. It is more convenient to use while(sc.hasNext) here, and char[] bytes = target The writing of .toCharArray is also worth learning.
    b. After the bracket string is stored in the char array, it is much more convenient. You can use the top element of the stack to match the next character in the array.
import java.util.Scanner;
import java.util.Stack;

public class SymbolMatch {
    public static void main(String[] args) {
        Stack<Character> stack = new Stack<Character>();
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String target = sc.nextLine();
            char[] bytes = target.toCharArray();
            // push the first character onto the stack
            stack.push(bytes[0]);
            /*
             * Starting from the second character, match the characters in the stack in turn
             */
            for (int i = 1; i < bytes.length; ++i) {
                Character c1 = (Character) stack.peek();
                Character c2 = bytes[i];
                if ((c1.toString().equals("(") && c2.toString().equals(")"))
                        || (c1.toString().equals("[") && c2.toString().equals("]"))
                        || (c1.toString().equals("{") && c2.toString().equals("}"))) {
                    stack.pop();
                } else {
                    stack.push(c2);
                }
            }
            boolean isMatch = stack.isEmpty();
            System.out.println("Content in stack: " + stack);
            System.out.println("Bracket matching result: " + isMatch);
        }
        sc.close();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324858054&siteId=291194637