发布网友
共1个回答
热心网友
import java.io.File;
import java.io.FileNotFoundException;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
public class TestParenthese {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
File myFile = new File("test.txt");
try {
Scanner input = new Scanner(myFile);
String aLine;
int x = input.nextInt();
// 分别创建两个字符串来保存括号对的左括号和右括号
String openParentheses = "";
String closeParentheses = "";
System.out.println("run:\n======================================================================");
System.out.println("Parentheses:");
for (int i = 0; i < x; i++) {
// Scanner类取完int后再读取字符串可能会出现取到的值为空的情况,
// 所以这里判断如果读取出来的是空行就再读取
do {
aLine = input.nextLine();
} while (aLine.isEmpty());
System.out.print(aLine + '\t');
openParentheses += aLine.charAt(0);
closeParentheses += aLine.charAt(1);
}
System.out.println("\n======================================================================");
while (input.hasNextLine()) {
aLine = input.nextLine();
if (aLine.trim().isEmpty()) { // 按照示例,如果是空行则退出显示
break;
}
Stack<Character> stack = new Stack<Character>();
boolean success = true;
for (int i = 0; i < aLine.length(); i++) {
char ch = aLine.charAt(i);
System.out.print(ch);
if (openParentheses.indexOf(ch) != -1) {
stack.push(ch);
} else if (closeParentheses.indexOf(ch) != -1) {
char open;
try {
open = stack.pop();
} catch (EmptyStackException e) {
System.out.println(" **MISMATCH: Too many parentheses");
success = false;
break;
}
if (openParentheses.indexOf(open) != closeParentheses.indexOf(ch)) {
System.out.printf(" **MISMATCH: %c should be %c\n", ch,
closeParentheses.charAt(openParentheses.indexOf(open)));
success = false;
break;
}
}
}
if (success) {
if (!stack.isEmpty())
System.out.println(" **MISMATCH: Not enough parentheses");
else
System.out.println("\t**GOOD");
}
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("======================================================================");
long endTime = System.currentTimeMillis();
long sec = (endTime - startTime) / 1000;
System.out.printf("BUILD SUCCESSFULLY (total time: %d seconds)\n", sec);
}
}