题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); System.out.println(matchStr(str)); } in.close(); } private static String matchStr(String input) { String[] arr_input = input.split(" "); 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"); map.put("matchFailed", "unknown command"); Set<String[]> set = new HashSet<>(); String match = "matchFailed"; int matchCount = 0; for (String str1 : map.keySet()) { set.add(str1.split(" ")); } for (String[] s : set) { if (s.length == 2) { if (arr_input.length == 2) { if (s[0].startsWith(arr_input[0]) && s[1].startsWith(arr_input[1])) { match = s[0] + " " + s[1]; matchCount++; } } } else { if (arr_input.length == 1) { if (s[0].startsWith(arr_input[0])) { match = s[0]; matchCount++; } } } } return matchCount > 1 ? "unknown command" : map.get(match); } }