题解 | #配置文件恢复#
配置文件恢复
http://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.util.*; public class Main { public static void main(String[] args) { String[] command = {"reset", "reset board", "board add", "board delete", "reboot backplane", "backplane abort"}; String[] syso = {"reset what", "board fault", "where to add", "no board at all", "impossible", "install first"}; Scanner scan = new Scanner(System.in); while (scan.hasNext()) { String s = scan.nextLine(); System.out.println(outPut(s, command, syso)); } } public static String outPut(String s, String[] command, String[] syso) { if (s == null || s.length() == 0) return ""; String[] arr = s.split(" "); if (arr.length == 1) { //单串 for (int i = 0; i < command.length; i++) { int p = 0; while (p < s.length() && s.charAt(p) == command[i].charAt(p)) { p++; if (p == s.length()) { if (command[i].split(" ").length > 1) return "unknown command"; return syso[i]; } } } return "unknown command"; } else if (arr.length == 2) { List<String> res = new ArrayList<>(); String s1 = arr[0]; String s2 = arr[1]; List<String> maybe = new ArrayList<>(); for (int i = 1; i < command.length; i++) { String[] arr1 = command[i].split(" "); String str = arr1[0]; if (s1.length() > str.length()) continue; int p = 0; while (p < s1.length() && s1.charAt(p) == str.charAt(p)) { p++; if (p == s1.length()) maybe.add(command[i]); } }//把所有第一轮可疑的都收进maybe里面了 if (maybe.size() == 0) return "unknown command"; for (int i = 0; i < maybe.size(); i++) { String[] arr2 = maybe.get(i).split(" "); String str = arr2[1]; if (s2.length() > str.length()) continue; int p = 0; while (p < s2.length() && s2.charAt(p) == str.charAt(p)) { p++; if (p == s2.length()) res.add(maybe.get(i)); } } if (res.size() == 0 || res.size() > 1) return "unknown command"; for (int i = 1; i < command.length; i++) { if (res.get(0).equals(command[i])){ return syso[i]; } } return "unknown command"; }else { return "unknown command"; } } }