题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.util.*; import java.util.regex.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 // while (in.hasNextInt()) { // 注意 while 处理多个 case // int a = in.nextInt(); // int b = in.nextInt(); // System.out.println(a + b); // } String[] commands = {"reset", "reset board", "board add", "board delete", "reboot backplane", "backplane abort"}; String[] results = {"reset what", "board fault", "where to add", "no board at all", "impossible", "install first", "unknown command"}; while (in.hasNextLine()) { String command = in.nextLine(); String[] subs = command.split(" "); int sublen = subs.length; StringBuilder builder = new StringBuilder(); for (int i = 0; i < sublen; i++) { if (i == 0) { builder.append("^" + subs[i] + "[a-z]" + "*"); } else { builder.append(" +" + subs[i] + "[a-z]" + "*"); } } command = builder.toString(); Pattern pattern = Pattern.compile(command); int count = 0; int index = -1; for (int i = 0; i < commands.length; i++) { String s = commands[i]; Matcher matcher = pattern.matcher(s); if (matcher.find()) { if (sublen == 1 && !s.contains(" ")) { count++; index = i; break; } else if (sublen > 1) { count++; index = i; } } } if (count == 1 && index != -1) { System.out.println(results[index]); } else { System.out.println(results[6]); } } } }