括号配对问题
描述
现在,有一行括号序列,请你检查这行括号是否配对。
3 [(]) (]) ([[]()])
No No Yes
Java实现
private static void fun() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Stack<Character> s = new Stack<Character>();
while (n != 0) {
String str = sc.next();
if (str.length() % 2 == 1) {
System.out.println("NO");
} else {
for (int index = 0; index < str.length(); index++) {
if (s.isEmpty()) {
s.push(str.charAt(index));
} else if ((s.peek() == '[' && str.charAt(index) == ']')
|| (s.peek() == '(' && str.charAt(index) == ')')) {
s.pop();
} else {
s.push(str.charAt(index));
}
}
if (s.isEmpty()) {
System.out.println("YES");
}else{
System.out.println("NO");
}
}
n--;
}
}
浙公网安备 33010602011771号