题解 | #配置文件恢复#

配置文件恢复

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

这道题注意题意:

1、如果字符串长度不匹配,一定是不会找到值

2、如果字符串相等

是长度为1的那种相等,还是长度为2的那种相等。

如果是长度为2的那种相等,必须切记,如果找到两个以上,则跟没找到是一个意思了。

时空复杂度O(n)

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    private static String defa = "unknown command";
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Map<String, String> map = new HashMap<>();
        map.put("reset", "reset what");
        map.put("reset board", "board fault");
        map.put("board add", "where to add");
        map.put("board delete", "no board at all");
        map.put("reboot backplane", "impossible");
        map.put("backplane abort", "install first");

        while (in.hasNextLine()) {
            getRecommend(in.nextLine(), map);
        }
    }

    private static void getRecommend(String string, Map<String, String> map) {
        String[] strs = string.split(" ");
        int len = strs.length;
        String result = defa;
        Set<String> set = map.keySet();

        for (String tt : set) {
            if (tt.startsWith(strs[0])) {
                //俩都按照长度为1,比较
                int ttLen = tt.split(" ").length;
                if (ttLen == 1 && len == 1) {

                    result = map.get(tt);
                }
                if ((len == 1 && ttLen > 1) || (len > 1 && ttLen == 1)) {
                    continue;
                }
                if (len == 2 && ttLen == 2) {
                    //比较两段相同

                    if (tt.split(" ")[1].startsWith(strs[1])) {

                        if (!result.equals(defa)) {
                            result = defa;
                        } else {

                            result = map.get(tt);
                        }

                    }


                }
            }
        }

        System.out.println(result);


    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:24
大家还是用ai改吧,我心疼得要死,就当花钱买教训吧,人家直接拿完钱就跑路了
程序员小白条:简历修改700....神奇,又不是帮你面试,咋的,简历修改从双非变92了还是没实习变成有大厂实习了
点赞 评论 收藏
分享
06-02 15:53
阳光学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务