题解 | #配置文件恢复#

配置文件恢复

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

import java.util.*;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static Map<String,String> configMap = new HashMap<>();
    public static Set<String> configSetOne = new HashSet<>();
    public static Set<String> configSetTwo = new HashSet<>();
    static {
    configMap.put("reset","reset what");
    configMap.put("reset board","board fault");
    configMap.put("board add","where to add");
    configMap.put("board delete","no board at all");
    configMap.put("reboot backplane","impossible");
    configMap.put("backplane abort","install first");
    configSetOne = configMap.keySet().stream().filter(str->str.split(" ").length==1).collect(Collectors.toSet());
    configSetTwo = configMap.keySet().stream().filter(str->str.split(" ").length==2).collect(Collectors.toSet());
    }
    public static final String UNKNOWN_COMMAND = "unknown command";
    public static void main(String[] args) {
        run();
    }

    private static void run() {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str = in.nextLine();
            String result = configFileRecovery(str);
            System.out.println(result);
        }
    }

    private static String configFileRecovery(String str) {
        String[] split = str.split(" ");
        int configCount=0;
        if (split.length==1) {
            String temp = "";
            for (String configStr : configSetOne) {
                if(configStr.startsWith(str)){
                    configCount++;
                    temp = configMap.get(configStr);
                }
            }
		  //只有唯一匹配的时候才返回结果
            if(configCount==1){
                return temp;
            }
        }else if(split.length==2){
            String temp = "";
            for (String configTwo : configSetTwo) {
                String[] configTwoArr = configTwo.split(" ");
                if(configTwoArr[0].startsWith(split[0])){
                    if(configTwoArr[1].startsWith(split[1])){
                        temp = configMap.get(configTwo);
                        configCount++;
                    }
                }
            }
		  //只有唯一匹配的时候才返回结果
            if(configCount==1){
                return temp;
            }
        }
        return UNKNOWN_COMMAND;
    }
}

全部评论

相关推荐

04-14 20:10
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务