Java Luogu P1739 expression bracket matching

Title description:
insert image description here

insert image description here
Topic link: https://www.luogu.com.cn/problem/P1739
Code example:


import java.util.Scanner;
import java.util.Stack;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        Stack<Character> stack = new Stack<>(); // 将左括号入栈
        boolean flag = true;
        for (int i = 0; i < str.length(); i++) {
    
    
            char a = str.charAt(i);
            if (str.charAt(i) == '(') {
    
    
                stack.push(a);
            } else if (str.charAt(i) == ')') {
    
    
                if (stack.empty()) {
    
    
                    flag = false;
                    break;
                } else {
    
    
                    // 弹出一个左括号
                    stack.pop();
                }
            }
        }
        if (flag && stack.empty()) {
    
    
            System.out.println("YES");
        } else {
    
    
            System.out.println("NO");
        }
    }
}

Test Results:

insert image description here

Guess you like

Origin blog.csdn.net/qq_43290288/article/details/129101232