题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.io.IOException;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
HashMap<String, String> map = new HashMap();
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");
while(sc.hasNextLine()){
String input = sc.nextLine();
String output = match(input, map);
System.out.println(output);
}
}
private static String match(String input, HashMap<String, String> map) {
// 处理特殊情况
String[] tokens = input.split(" ");
if(tokens.length == 1){
if("reset".indexOf(tokens[0]) == 0){
return "reset what";
} else {
return "unknown command";
}
}
if(tokens.length > 2){
return "unknown command";
}
// 遍历Hash表,看看又没有匹配的
int count = 0;
String key = null;
for (Map.Entry<String, String> entry : map.entrySet()) {
String[] keys = entry.getKey().split(" ");
if(keys[0].indexOf(tokens[0]) == 0){
if (keys[1].indexOf(tokens[1]) == 0){
count++;
key = entry.getKey();
}
}
}
// 匹配一个的则匹配成功,匹配0个或多个则匹配失败
if(count == 1){
return map.get(key);
} else{
return "unknown command";
}
}
}
查看11道真题和解析
