题解 | #配置文件恢复#

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

这道题关键是会使用startsWith函数以及懂得用哈希表存储命令行键值对,从而去匹配。
import java.util.*;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        
        Map<String,String>command=new HashMap<String,String>();//建立哈希表
        //向哈希表里添加键值对
        command.put("reset","reset what");
        command.put("reset board","board fault");
        command.put("board add","where to add");
        command.put("reboot backplane","impossible");
        command.put("backplane abort","install first");
        command.put("board delete","no board at all");
        command.put("not match","unknown command");
        
        Set<String []> str=new HashSet<>();
        //将命令行里的字符串的每个单词分别存储到集合Str里
        for(String s:command.keySet()){
            str.add(s.split(" "));
        }
        
        while(sc.hasNextLine()){
            String []arr=sc.nextLine().split(" "); //将输入的字符串按空格前后分割成数组
            String res="not match";
            int count=0;
            for(String[]s: str){
                if(arr.length==1){
                    if(s.length==2)        //单字符匹配到的双关键字命令 则不成功跳过
                        continue;
                    else{
                        if(s[0].startsWith(arr[0]))
                        {
                            res=s[0];
                            count++;
                        }
                    }
                }
                
                if(arr.length==2){
                    if(s.length==1){    //双字符匹配到单关键字命令,跳过
                        continue;
                    }
                    else{
                        if(s[0].startsWith(arr[0])&&s[1].startsWith(arr[1])){
                            res=s[0]+" "+s[1];
                            count++;
                        }
                    }
                }
            }
            System.out.println(count>1?"unknown command":command.get(res));
        }
    }
}


全部评论

相关推荐

06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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