题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.util.*;
/**
最短唯一匹配:从首字母开始匹配
匹配关键字, 第一关键字优先第二,匹配唯一
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 存储要匹配的命令
Map<String, String> map = new HashMap<>();
map.put("reset", "reset what");
map.put("reset board", "board fault");
map.put("board add", "where to add");
map.put("board delete", "no board at all");
map.put("reboot backplane", "impossible");
map.put("backplane abort", "install first");
String ERROR = "unknown command";
while (in.hasNextLine()) { // 注意 while 处理多个 case
//默认有两个关键字
String s = in.nextLine();
int onlyOne = 0; //保证唯一性
String outPut = new String();
String[] arr = s.split(" ");
for (String key : map.keySet()) {
String[] arrK = key.split(" ");
if (arr.length == 1 && arrK.length == 1) {
//判断一个关键字
String k1 = arrK[0].substring(0, Math.min(arr[0].length(), arrK[0].length()));
if (k1.equals(arr[0])) {
onlyOne++;
if (onlyOne == 1) {
outPut = map.get(key);
} else {
System.out.println(ERROR);
break;
}
}
}
if (arr.length == 2 && arrK.length == 2) {
//判断两个关键字
String k1 = arrK[0].substring(0, Math.min(arr[0].length(), arrK[0].length()));
String k2 = arrK[1].substring(0, Math.min(arr[1].length(), arrK[1].length()));
if (k1.equals(arr[0]) && k2.equals(arr[1])) {
onlyOne++;
if (onlyOne == 1) {
outPut = map.get(key);
} else {
System.out.println(ERROR);
break;
}
}
}
}
if(onlyOne == 1){
System.out.println(outPut);
}
if(onlyOne == 0){
System.out.println(ERROR);
}
}
}
}
