题解 | #配置文件恢复#

配置文件恢复

https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5

import java.util.*;

public class Main {
    static final String UNKNOWN_COMMAND = "unknown command";
    static final Map<String, String> DICT = new HashMap<String, String>() {
        {
            put("reset", "reset what");
            put("reset board", "board fault");
            put("board add", "where to add");
            put("board delete", "no board at all");
            put("reboot backplane", "impossible");
            put("backplane abort", "install first");
        }
    };

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String command = in.nextLine();
            int index = command.indexOf(' ');
            // 一字串
            if (index == -1) {
                int count = 0;
                String v = null;
                for (Map.Entry<String, String> entry : DICT.entrySet()) {
                    String k = entry.getKey();
                    // 一字串只匹配一关键字命令
                    if (k.indexOf(' ') == -1 && k.indexOf(command) == 0) {
                        count++;
                        v = entry.getValue();
                    }
                    if (count > 1) {
                        break;
                    }
                }
                if (count == 1) {
                    System.out.println(v);
                } else {
                    System.out.println(UNKNOWN_COMMAND);
                }
            // 两字串
            } else {
                int count = 0;
                String v = null;
                String c1 = command.substring(0, index);
                String c2 = command.substring(index + 1);
                for (Map.Entry<String, String> entry : DICT.entrySet()) {
                    String k = entry.getKey();
                    int ki = k.indexOf(' ');
                    if (ki != -1) {
                        String k1 = k.substring(0, ki);
                        String k2 = k.substring(ki + 1);
                        if (k1.indexOf(c1) == 0 && k2.indexOf(c2) == 0) {
                            count++;
                            v = entry.getValue();
                        }
                        if (count > 1) {
                            break;
                        }
                    }
                }
                if (count == 1) {
                    System.out.println(v);
                } else {
                    System.out.println(UNKNOWN_COMMAND);
                }
            }
        }
    }
}

#华为笔试#
全部评论

相关推荐

10-06 12:46
门头沟学院 Java
跨考小白:定时任务启动
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:19
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务