题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.util.*; public class Main { // 定义命令及其对应的输出 private static final Map<List<String>, String> commands = new HashMap<List<String>, String>() {{ put(Arrays.asList("reset"), "reset what"); put(Arrays.asList("reset", "board"), "board fault"); put(Arrays.asList("board", "add"), "where to add"); put(Arrays.asList("board", "delete"), "no board at all"); put(Arrays.asList("reboot", "backplane"), "impossible"); put(Arrays.asList("backplane", "abort"), "install first"); }}; public static List<String> processCommands(List<String> inputs) { List<String> results = new ArrayList<>(); for (String input : inputs) { String[] keywords = input.split(" "); List<List<String>> matches = new ArrayList<>(); // 遍历命令集,查找符合输入的最短唯一匹配 for (List<String> command : commands.keySet()) { boolean match = true; // 检查每个关键字是否匹配 for (int i = 0; i < keywords.length; i++) { if (i >= command.size() || !command.get(i).startsWith(keywords[i])) { match = false; break; } } if (match && command.size() == keywords.length) { // 确保输入的关键字数量和命令的关键字数量一致 matches.add(command); } } // 根据匹配结果确定输出内容 if (matches.size() == 1) { results.add(commands.get(matches.get(0))); } else { results.add("unknown command"); } } return results; } public static void main(String[] args) { Scanner fzhinput = new Scanner(System.in); List<String> inputs = new ArrayList<>(); // 逐行接收输入,直到遇到空行或没有更多行 while (fzhinput.hasNextLine()) { String input = fzhinput.nextLine().trim(); if (input.isEmpty()) break; inputs.add(input); } // 处理输入并输出结果 List<String> output = processCommands(inputs); output.forEach(System.out::println); fzhinput.close(); } }