题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 创建命令和执行结果的对应哈希表 HashMap<String,String> table = new HashMap<String,String>(); table.put("reset","reset what"); table.put("reset board","board fault"); table.put("board add","where to add"); table.put("board delete","no board at all"); table.put("reboot backplane","impossible"); table.put("backplane abort","install first"); // 创建命令的字符串数组集合:每个元素是一个数组,数组长度为1或2 Set<String[]> order = new HashSet<String[]>(); for (String s : table.keySet()) { // 先把每一条命令拆分成数组再加到集合中 order.add(s.split(" ")); } while (in.hasNextLine()) { String str = in.nextLine(); // 把输入的字符串变为字符串数组 String[] inputChange = str.split(" "); // 用于匹配的命令 String[] compitable = null; // 记录匹配的命令个数 int count = 0; for (String[] cmpOrder : order) { if (inputChange.length == 1) { if (cmpOrder.length == 2) { continue; }else { // 是否以指定前缀开始 if (cmpOrder[0].startsWith(inputChange[0])) { count++; compitable = cmpOrder; continue; } } } if (inputChange.length == 2) { if (cmpOrder.length == 1) { continue; }else { if (cmpOrder[0].startsWith(inputChange[0])) { if (cmpOrder[1].startsWith(inputChange[1])) { count++; compitable = cmpOrder; continue; } } } } } if (compitable == null || count == 2) System.out.println("unknown command"); else if (compitable.length == 1) System.out.println(table.get(compitable[0])); else System.out.println(table.get(compitable[0] + " " + compitable[1])); } in.close(); } }