题目描述:
题目链接:https://www.luogu.com.cn/problem/P1739
代码实例:
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");
}
}
}
测试结果: