题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
这道题注意题意:
1、如果字符串长度不匹配,一定是不会找到值
2、如果字符串相等
是长度为1的那种相等,还是长度为2的那种相等。
如果是长度为2的那种相等,必须切记,如果找到两个以上,则跟没找到是一个意思了。
时空复杂度O(n)
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { private static String defa = "unknown command"; 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"); while (in.hasNextLine()) { getRecommend(in.nextLine(), map); } } private static void getRecommend(String string, Map<String, String> map) { String[] strs = string.split(" "); int len = strs.length; String result = defa; Set<String> set = map.keySet(); for (String tt : set) { if (tt.startsWith(strs[0])) { //俩都按照长度为1,比较 int ttLen = tt.split(" ").length; if (ttLen == 1 && len == 1) { result = map.get(tt); } if ((len == 1 && ttLen > 1) || (len > 1 && ttLen == 1)) { continue; } if (len == 2 && ttLen == 2) { //比较两段相同 if (tt.split(" ")[1].startsWith(strs[1])) { if (!result.equals(defa)) { result = defa; } else { result = map.get(tt); } } } } } System.out.println(result); } }