题目
Description
现在,有一行括号序列,请你检查这行括号是否配对。
Input
第一行输入一个数N<=1000)后面是N行由组成的括号序列~
Output
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
Sample Input
No
No
Yes
代码块
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner cn = new Scanner(System.in);
int t = cn.nextInt();
Stack<Character> sta = null;
while (t-- > 0) {
String str = cn.next();
if (str.length() % 2 == 1)
System.out.println("No");
else {
sta = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
//是空的就入栈
if (sta.isEmpty())
sta.push(str.charAt(i));
//有匹配的就出栈
else if (sta.peek() == '[' && str.charAt(i) == ']'
|| sta.peek() == '(' && str.charAt(i) == ')'
|| sta.peek() == '{' && str.charAt(i) == '}')
sta.pop();
//不匹配的也入栈
else
sta.push(str.charAt(i));
}
if (sta.isEmpty())
System.out.println("Yes");
else
System.out.println("No");
}
}
cn.close();
}
}