华为机试:配置文件恢复、四则运算

来源:互联网 发布:新加坡apache国际集团 编辑:程序博客网 时间:2024/06/06 04:03

1.配置文件恢复

题目描述

有6条配置命令,它们执行的结果分别是:

<colgroup><col style="width&#58;181px&#59;" width="181"/><col style="width&#58;347px&#59;" width="346"/></colgroup>命   令执   行resetreset whatreset boardboard faultboard addwhere to addboard deletno board at allreboot backplaneimpossiblebackplane abortinstall firsthe heunkown command

  注意:he he不是命令。

为了简化输入,方便用户,以“最短唯一匹配原则”匹配:
1、若只输入一字串,则只匹配一个关键字的命令行。例如输入:r,根据该规则,匹配命令reset,执行结果为:reset what;输入:res,根据该规则,匹配命令reset,执行结果为:reset what; 
2、若只输入一字串,但本条命令有两个关键字,则匹配失败。例如输入:reb,可以找到命令reboot backpalne,但是该命令有两个关键词,所有匹配失败,执行结果为:unkown command 
3、若输入两字串,则先匹配第一关键字,如果有匹配但不唯一,继续匹配第二关键字,如果仍不唯一,匹配失败。例如输入:r b,找到匹配命令reset board,执行结果为:board fault。

4、若输入两字串,则先匹配第一关键字,如果有匹配但不唯一,继续匹配第二关键字,如果唯一,匹配成功。例如输入:b a,无法确定是命令board add还是backplane abort,匹配失败。
5、若输入两字串,第一关键字匹配成功,则匹配第二关键字,若无匹配,失败。例如输入:bo a,确定是命令board add,匹配成功。
6、若匹配失败,打印“unkown command”


输入描述:

多行字符串,每行字符串一条命令

输出描述:

执行结果,每条命令输出一行

示例1

输入

resetreset boardboard addboard deletreboot backplanebackplane abort

输出

reset whatboard faultwhere to addno board at allimpossibleinstall first

解法1:

利用hashmap键的匹配,然后取出对应的值,虽然通过所有的测试用例了,但是感觉不怎么好,比如说我输入r。

import java.util.HashMap;import java.util.Scanner;public class Main {public static void main(String[] args) {HashMap<String, String> map = new HashMap<String,String>();map.put("reset", "reset what");map.put("reset board", "board fault");map.put("board add", "where to add");map.put("board delet", "no board at all");map.put("reboot backplane", "impossible");map.put("backplane abort", "install first");Scanner sc=new Scanner(System.in);        while(sc.hasNext()){        //第一次用的sc.next(),编译始终不通过。后来发现输入中有空格。            String str=sc.nextLine();            if(map.containsKey(str)){//检测是否包含此键            System.out.println(map.get(str));            }else{            System.out.println("unkown command");            }        }}}

解法2:

利用字符串的contains()方法挨个匹配,然后输出。

import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while(scanner.hasNext()){String str=scanner.nextLine();if("reset".contains(str)){System.out.println("reset what");}else if("reset board".contains(str)){System.out.println("board fault");}else if("board add".contains(str)){System.out.println("where to add");}else if("board delet".contains(str)){System.out.println("no board at all");}else if("reboot backplane".contains(str)){System.out.println("impossible");}else if("backplane abort".contains(str)){System.out.println("install first");}else{System.out.println("unkown command");}}}}


2.四则运算