描述:
现在,有一行括号序列,请你检查这行括号是否配对。
输入:
第一行输入一个数N(0
import java.util.Scanner;
import java.util.Stack;
public class Demo01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String[] str = new String[num];
for(int i = 0;i < num;i++){
str[i] = sc.next();
}
for(int i = 0;i<num;i++){
if(matchInfo(str[i]) == true){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
public static boolean matchInfo(String str){
Stack<Character> stack = new Stack<Character>();
char[] ca = str.toCharArray();
if(((Character)ca[0]=='[') || ((Character)ca[0]=='(')){
for(int index=0;index<ca.length;index++){
Character c1 = (Character)ca[index];
if((c1=='[') || (c1=='(')){
stack.push(c1);
}else if(stack.empty()==true){//测试堆栈是否为空
return false;
}else if((c1==']') || (c1==')') ){
//peek()查看栈顶的对象,但是并不移除它
if(((((Character)stack.peek()) == '(') && (c1 == ')')) || ((((Character)stack.peek()) == '[') && (c1==']'))){
stack.pop();//移除栈顶的值,并作为此函数的值返回该对象
}
else{
return false;
}
}
}
//测试堆栈是否为空,当且仅当堆栈中不含任何项时返回true,否则返回false
return stack.empty();
}
else return false;
}
}