题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String[] commands = new String[] {"reset", "reset board", "board add", "board delete", "reboot backplane", "backplane abort", "he he"}; String[] implts = new String[] {"reset what", "board fault", "where to add", "no board at all", "impossible", "install first", "unknown command"}; int[] indArr = new int[] {0, 6, 6, 6, 7, 10}; String a, console = ""; char[] chs; char[] comd; int i, j, l, cnt, index, lc, match, matchInx; boolean invalid; try { while ((a = r.readLine()) != null && !a.isEmpty()) { chs = a.toCharArray(); l = chs.length; i = 0; cnt = 1; index = 0; while (i < l) { if (chs[i] == ' ') { if (i + 1 < l && chs[i + 1] != ' ') index = i + 1; cnt++; } i++; } if (cnt == 1) { invalid = false; comd = commands[0].toCharArray(); if (l > comd.length) { console = console + implts[6] + "\n"; continue; } i = 0; while (i < l) { if (chs[i] != comd[i]) { invalid = true; break; } i++; } if (invalid) console = console + implts[6] + "\n"; else console = console + implts[0] + "\n"; continue; } if (cnt > 2) { console = console + implts[6] + "\n"; continue; } i = 1; match = 0;//匹配的数量 matchInx = 6;//匹配的索引 while (i < 6) { invalid = false;//由于遍历时,一个新的命令开始时,判断重新开始,因此invalid初始为false comd = commands[i].toCharArray(); lc = comd.length; if (index > indArr[i] || l - index > lc - indArr[i]) {//不匹配 i++; continue; } j = 0; while (j < index - 1) {//第一个单词是否匹配 if (chs[j] != comd[j]) { invalid = true; break; } j++; } j = 0; while (j < l - index) {//第二个单词是否匹配,以输入的字符串长度为准,因此为l-index if (chs[index + j] != comd[indArr[i] + j]) { invalid = true; break; } j++; } if (!invalid) { matchInx = i;//匹配索引赋值 match++;//匹配数量自加 } i++; } if (match != 1) console = console + implts[6] + "\n"; else console = console + implts[matchInx] + "\n"; } } catch (IOException e) { throw new RuntimeException(e); } System.out.print(console); } }