题解 | #配置文件恢复#

时常看不懂华为机试题的题目!!!

import java.util.*;
public class Main {
    static Map<String, String> commMap = new HashMap<>();

    public static void main(String[] args) {
        commMap.put("reset", "reset what");
        commMap.put("reset board", "board fault");
        commMap.put("board add", "where to add");
        commMap.put("board delete", "no board at all");
        commMap.put("reboot backplane", "impossible");
        commMap.put("backplane abort", "install first");
        Set<String[]> keySet = new HashSet<>();
        for (String key : commMap.keySet()) {
            keySet.add(key.split(" "));
        }

        /**
         题意剖析:
             输入一个字符串
                1)只能匹配一个关键字的命令行
             输入两个字符串,只能匹配长度为2的命令行
                1)若第一个字符串和第二个字符串的匹配结果不唯一,输出unkonw
                2)若不匹配,直接unkonw
             注意,最短唯一匹配!!!
         */
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String[] arr = sc.nextLine().trim().split(" ");
            if (arr.length == 1) {
                boolean match = false;
                for (String[] key : keySet) {
                    if (key.length == 1 && matchTest(arr[0], key[0])) {
                        System.out.println(commMap.get(key[0]));
                        match = true;
                        break;
                    }
                }
                if (!match) {
                    System.out.println("unknown command");
                }
            }

            if (arr.length == 2) {
                List<String> comm = new ArrayList<>();
                for (String[] key : keySet) {
                    if (key.length == 2 && matchTest(arr[0], key[0]) && matchTest(arr[1], key[1])) {
                        comm.add(key[0] + " " + key[1]);
                    }
                }
                if (comm.size() != 1) {
                    System.out.println("unknown command");
                } else {
                    System.out.println(commMap.get(comm.get(0)));
                }
            }
        }
    }

    public static boolean matchTest(String reg, String key) {
        for (int i = 0; i < reg.length(); i++) {
            if (reg.charAt(i) != key.charAt(i)) {
                return false;
            }
        }
        return true;
    }
}


全部评论

相关推荐

没有offer的呆呆:薪资有的时候也能说明一些问题,太少了活不活得下去是一方面,感觉学习也有限
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务