检查一段C语言代码的小括号( )、 中括号 [ ] 和大括号{ } 是否匹配。
输入格式:
在一行中输入一段C语言代码,长度不超过1000个字符(行末以换行符结束)。
输出格式:
第一行输出左括号的数量和右括号的数量,中间以一个空格间隔。
若括号是匹配的,在第二行打印YES,否则打印NO。
输入样例1:
for(int i=0; iAdj[i][j])); }
输出样例1:
8 8 YES
输入样例2:
for(int i=0; i输出样例2:
2 2 NOimport java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] s = sc.nextLine().toCharArray(); Stackstk = new Stack (); int left = 0, right = 0; for (char x : s) { if (left_kuohao(x)) { left++; stk.add(x); } else if (right_kuohao(x)) { right++; if (!stk.isEmpty() && match(stk.peek(), x)) { stk.pop(); } else { stk.add(x); } } } System.out.println(left + " " + right); if (left != right || !stk.isEmpty()) { System.out.println("NO"); } else { System.out.println("YES"); } } public static boolean left_kuohao(char x) { return x == '{' || x == '[' || x == '('; } public static boolean right_kuohao(char x) { return x == '}' || x == ']' || x == ')'; } public static boolean match(char a, char b) { return (a == '{' && b == '}') || (a == '(' && b == ')') || (a == '[' && b == ']'); } }



