描述
请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。
输入描述:
有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。
输出描述:
对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。
示例1
输入:
4 [(d+f)*{}] [(2+3)) ()} [4(6]7)9
输出:
yes no no no
代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
/*
* ProblemE:括号匹配
*/
public class ProblemE {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
int n = scanner.nextInt();
Loop:
for (int i = 0; i < n; i++) {
String str = scanner.next();
List<Character> myList = new ArrayList<Character>();
Stack<Character> myStack = new Stack<Character>();
for (int j = 0; j < str.length(); j++) {
myList.add(str.charAt(j));
}
while(!myList.isEmpty()) {
if (myList.get(0) == '(' || myList.get(0) == '{' || myList.get(0) == '[') {
myStack.push(myList.remove(0));
continue;
}else if (myList.get(0) == ')') {
if (myStack.isEmpty()) {
System.out.println("no");
continue Loop;
}else if (myStack.peek() != '(') {
System.out.println("no");
continue Loop;
}else {
myList.remove(0);
myStack.pop();
}
}else if (myList.get(0) == '}') {
if (myStack.isEmpty()) {
System.out.println("no");
continue Loop;
}else if (myStack.peek() != '{') {
System.out.println("no");
continue Loop;
}else {
myList.remove(0);
myStack.pop();
}
}else if (myList.get(0) == ']') {
if (myStack.isEmpty()) {
System.out.println("no");
continue Loop;
}else if (myStack.peek() != '[') {
System.out.println("no");
continue Loop;
}else {
myList.remove(0);
myStack.pop();
}
}else {
myList.remove(0);
continue;
}
}
if (myStack.isEmpty()) {
System.out.println("yes");
}else {
System.out.println("no");
}
}
}
}
}