题解 | #配置文件恢复#

配置文件恢复

https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5?tpId=37&tags=&title=&difficulty=&judgeStatus=&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26pageSize%3D100%26search%3D%26tpId%3D37%26type%3D37&gioEnter=menu

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        String[] command = new String[] {"reset", "reset board", "board add", "board delete", "reboot backplane", "backplane abort"};
        String[] execute = new String[] {"reset what", "board fault", "where to add", "no board at all", "impossible", "install first"};
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            int index = matchCommand(command, str);
            if (index != -1) {
                System.out.println(execute[index]);
            } else {
                System.out.println("unknown command");
            }
        }
    }

    /**
     * 从command中找到与str匹配的命令,并返回索引,所有没有,则返回-1
     */
    static int matchCommand(String[] command, String str) {
        //记录匹配的数量
        int n = 0;
        //匹配的索引
        int index = -1;
        for (int i = 0; i < command.length; i++) {
            if (isMatch(command[i],str)){
                n++;
                if (n >= 2){
                    return -1;
                }
                index = i;
            }
        }

        return index;
    }

    /**
     * command 和 str是否匹配
     */
    static boolean isMatch(String command, String str) {
        String[] strs = str.split(" ");
        String[] commands = command.split(" ");
        if (strs.length != commands.length) {
            return false;
        }

        for (int i = 0; i < strs.length; i++) {
            String curCommand = commands[i];
            String curStr = strs[i];
            for (int j = 0; j < strs[i].length(); j++) {
                if (curCommand.charAt(j) != curStr.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }
}

全部评论

相关推荐

牛客533433175号:更可气的是我做完这些给我拒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务