题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
Map<String, String> cmd1 = new HashMap<>();
Map<String, String> cmd2 = new HashMap<>();
cmd1.put("reset", "reset what");
cmd2.put("reset board", "board fault");
cmd2.put("board add", "where to add");
cmd2.put("board delete", "no board at all");
cmd2.put("reboot backplane", "impossible");
cmd2.put("backplane abort", "install first");
String errMsg = "unknown command";
while (in.hasNextLine()) {
String a = in.nextLine();
// 暴力解只有一串
if (a.split(" ").length == 1 && a.length() <= "reset".length()) {
boolean flag = true;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != "reset".charAt(i)) {
flag = false;
break;
}
}
System.out.println(flag ? cmd1.get("reset") : errMsg);
} else if (a.split(" ").length == 2) {
// 暴力解有且只有二串,遍历两串是否相符,比较耗时
String[] arr = a.split(" ");
Iterator<String> iter = cmd2.keySet().iterator();
int count = 0;
String key = "";
while (iter.hasNext()) {
String nextKey = iter.next();
String[] nextKeyArr = nextKey.split(" ");
boolean flag1 = true;
if (!nextKeyArr[0].startsWith(arr[0])) {
flag1 = false;
}
if (flag1) {
boolean flag2 = true;
if (!nextKeyArr[1].startsWith(arr[1])) {
flag2 = false;
}
if (flag2) {
count++;
key = nextKey;
}
}
}
System.out.println(count == 1 ? cmd2.get(key) : errMsg);
} else {
System.out.println(errMsg);
}
}
}
}