首页 > 试题广场 >

配置文件恢复

[编程题]配置文件恢复
  • 热度指数:111046 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

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

命   令 执   行
reset reset what
reset board board fault
board add where to add
board delete no board at all
reboot backplane impossible
backplane abort install first
he he unknown command

注意:he he不是命令。

为了简化输入,方便用户,以“最短唯一匹配原则”匹配(注:需从首字母开始进行匹配):

1、若只输入一字串,则只匹配一个关键字的命令行。例如输入:r,根据该规则,匹配命令reset,执行结果为:reset what;输入:res,根据该规则,匹配命令reset,执行结果为:reset what;
2、若只输入一字串,但匹配命令有两个关键字,则匹配失败。例如输入:reb,可以找到命令reboot backpalne,但是该命令有两个关键词,所有匹配失败,执行结果为:unknown command

3、若输入两字串,则先匹配第一关键字,如果有匹配,继续匹配第二关键字,如果仍不唯一,匹配失败。
例如输入:r b,找到匹配命令reset board 和 reboot backplane,执行结果为:unknown command。
例如输入:b a,无法确定是命令board add还是backplane abort,匹配失败。

4、若输入两字串,则先匹配第一关键字,如果有匹配,继续匹配第二关键字,如果唯一,匹配成功。例如输入:bo a,确定是命令board add,匹配成功。
5、若输入两字串,第一关键字匹配成功,则匹配第二关键字,若无匹配,失败。例如输入:b addr,无法匹配到相应的命令,所以执行结果为:unknow command。
6、若匹配失败,打印“unknown command”

注意:有多组输入。
数据范围:数据组数:,字符串长度
进阶:时间复杂度:,空间复杂度:

输入描述:

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



输出描述:

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

示例1

输入

reset
reset board
board add
board delet
reboot backplane
backplane abort

输出

reset what
board fault
where to add
no board at all
impossible
install first
import java.util.*;

public class Main {
	
	public static boolean isMatch(String src, String des){
		char[] c1 = src.toCharArray();
		char[] c2 = des.toCharArray();
		int i = 0;
		while(i < c1.length && i < c2.length){
			if(c1[i] == c2[i])
				i++;
			else
				break;
		}
		if(i == c1.length)
			return true;
		else 
			return false;
	}
	
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashMap<String, String> hMap = new HashMap<>();
        hMap.put("reset", "reset what");
        hMap.put("reset board", "board fault");
        hMap.put("board add", "where to add");
        hMap.put("board delet", "no board at all");
        hMap.put("reboot backplane", "impossible");
        hMap.put("backplane abort", "install first");
        while (scanner.hasNext()) {
        	String[] strs = scanner.nextLine().split(" ");
        	int count = 0; // 记录匹配个数
        	Set<String> set = hMap.keySet();
        	String key = "";
        	for(String s : set){
        		String[] temps = s.split(" ");
        		if(temps.length == strs.length){
        			int i = 0;
        			while(i < temps.length){
        				if(isMatch(strs[i], temps[i]))
        					i++;
        				else
        					break;
        			}
        			if(i == temps.length){ // 找到匹配
        				key = s;
        				count++;
        			}       				
        		}
        	}
        	if(count != 1)
        		System.out.println("unkown command");
        	else
        		System.out.println(hMap.get(key));
        		
        }
        scanner.close();
    }
}

发表于 2016-08-13 16:05:28 回复(3)
题目里的这句话是错的吧。
3、若输入两字串,则先匹配第一关键字,如果有匹配但不唯一,继续匹配第二关键字,如果仍不唯一,匹配失败。例如输入:r b,找到匹配命令reset board,执行结果为:board fault。
输入r b应该是不唯一的,执行结果应为
unkown command

附上我自己的代码

#include <iostream>
#include <vector>
#include <string>

using namespace std;

// 配置文件恢复

int main()
{
    vector<string> commandList = {"reset", "reset board", "board add", "board delet", "reboot backplane", "backplane abort"};
    vector<string> commandAction = {"reset what", "board fault", "where to add", "no board at all", "impossible", "install first"};

    string command;
    string error = "unkown command";

    while (getline(cin, command))
    {
        vector<string> givenCommand;
        string thisCommand;
        for (int i = 0; i < command.size(); ++i)
        {
            if (command[i] == ' ')
            {
                if (thisCommand.size() > 0)
                {
                    givenCommand.push_back(thisCommand);
                    thisCommand = "";
                }
            }
            else
            {
                thisCommand.append(1, command[i]);
            }
        }
        if (thisCommand.size() > 0)
        {
            givenCommand.push_back(thisCommand);
        }

        if (givenCommand.size() == 1)
        {
            if (commandList[0].compare(0, givenCommand[0].size(), givenCommand[0]) == 0)
            {
                cout << commandAction[0] << endl;
            }
            else
            {
                cout << error << endl;
            }
        }
        else if (givenCommand.size() == 2)
        {
            int matchNum = 0;
            int matchIndex = 0;
            for (int j = 1; j < commandList.size(); ++j)
            {
                int comp1 = commandList[j].compare(0, givenCommand[0].size(), givenCommand[0]);
                unsigned long long int index2 = commandList[j].find(' ');
                int comp2 = commandList[j].compare((index2 + 1), givenCommand[1].size(), givenCommand[1]);

                if (comp1 == 0 && comp2 == 0)
                {
                    ++matchNum;
                    matchIndex = j;
                }
            }

            if (matchNum == 1)
            {
                cout << commandAction[matchIndex] << endl;
            }
            else
            {
                cout << error << endl;
            }
        }
        else
        {
            cout << error << endl;
        }
    }

    return 0;
}

编辑于 2016-08-13 15:51:29 回复(6)
import java.util.*;
public class Main{
    public static void main(String[]args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String s=sc.nextLine();
            recover(s);
        }
    }
    public static void recover(String s){
        String[]strings={"reset","reset board","board add","board delete","reboot backplane","backplane abort","he he"};
        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");
        map.put("he he","unknown command");
        String[]str=s.split(" ");
        if (str.length==1){
            String ss=strings[0].substring(0,str[0].length());
            if (ss.equals(str[0])){
                System.out.println("reset what");
            }else {
                System.out.println("unknown command");
            }
        }else {
            int count=0;
            String flag="";
            for (int i=1;i<strings.length;i++){
                String st=strings[i];
                String[]st1=st.split(" ");
                if (st1.length==2){
                    if (st1[0].length()<str[0].length() || st1[1].length()<str[1].length()){
                        continue;
                    }
                    String s1=st1[0].substring(0,str[0].length());
                    String s2=st1[1].substring(0,str[1].length());
                    if (s1.equals(str[0]) && s2.equals(str[1])){
                        count++;
                        flag=st;
                    }
                }
            }
            if (count==1){
                System.out.println(map.get(flag));
            }else {
                System.out.println("unknown command");
            }
        }
    }

}
1、只按照前缀匹配。如果输入的是一个单词中间的字母,匹配不了。
2、把每一个字符都拆开,截取输入字母的长度。
变量命名太多了。好绕。

发表于 2021-10-24 22:22:29 回复(0)
import re
cmd = ('reset', 'reset board', 'board add', 'board delete', 'reboot backplane', 'backplane abort')
res = ('reset what', 'board fault', 'where to add', 'no board at all', 'impossible', 'install first', 'unknown command')
while True:
    try:
        s = input().strip().split()
        match1_cmd = [] # 第一个关键字 匹配到的
        for j, v in enumerate(cmd):
            if re.match(s[0], v):   # 匹配以该关键字开头的
                if len(s) == 1 and len(v.split()) == 1:
                    match1_cmd.append((cmd[j], res[j]))
                elif len(s) == 2 and len(v.split()) ==2:
                    match1_cmd.append((cmd[j], res[j]))
        if len(s) == 1:
            if len(match1_cmd) == 1:
                print(match1_cmd[0][1])
            else:
                print(res[-1])
        else:
            match2_cmd = [] # 如果关键字 长度为2 继续匹配后一个管关键字
            for i in match1_cmd:
                if re.match(s[1], i[0].split()[1]):
                    match2_cmd.append(i)
            if len(match2_cmd) == 1:
                print(match2_cmd[0][1])
            else:
                print(res[-1])
    except:
        break
        

发表于 2020-09-29 23:18:10 回复(0)
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
vector<pair<pair<string, string>, string>> helper{
	{{"reset",""},"reset what"},{ {"reset","board"},"board fault" },{ {"board","add"},"where to add" },
	{ {"board","delet"},"no board at all" }, { {"reboot","backplane"},"impossible" },
	{ {"backplane","abort"},"install first" } };
int main() {
	string str;
	while (getline(cin,str)) {
		int _count = count(str.begin(), str.end(), ' ');
		if (_count == 0)
			if (helper[0].first.first.find(str) != string::npos)
				cout << helper[0].second << endl;
			else cout << "unkown command" << endl;
		else if (_count == 1 && str[str.size() - 1] != ' ') {
			int flag = 0;
			string tmp;
			string part1 = str.substr(0, str.find(' '));
			string part2 = str.substr(str.find(' ') + 1);
			for (auto p : helper) {
				if (p.first.first.find(part1) != string::npos &&
					p.first.second.find(part2) != string::npos) {
					++flag;
					if (flag == 2) break;
					tmp = p.second;
				}
			}
			if (flag == 1) cout << tmp << endl;
			else cout<< "unkown command" << endl;
		}
		else cout << "unkown command" << endl;
	}
}

发表于 2017-03-18 14:15:14 回复(1)
while True:
    try:
        command_keys = [
            "reset",
            "reset board",
            "board add",
            "board delete",
            "reboot backplane",
            "backplane abort",
        ]
        command_values = [
            "reset what",
            "board fault",
            "where to add",
            "no board at all",
            "impossible",
            "install first",
        ]

        cmd = input()
        cmd_split = cmd.split()

        if len(cmd_split) == 1 and cmd == command_keys[0][0 : len(cmd)]:
            print(command_values[0])
        elif len(cmd_split) == 2:
            flag = 0  # 保存第二个匹配次数,若为1,则返回对应命令;若大于1,则返回unknown command
            match_cmd = ""  # 保存匹配到的命令

            # 遍历,如果遇到匹配的,flag + 1
            # 匹配到的条件是第一个字串和第二各字串同时匹配上
            # flag = 1,说明只有一个匹配的
            # flag > 1,说明有多于一个匹配的,根据题设,则匹配失败
            for i in range(1, 6):
                command_keys_split = command_keys[i].split()
                if command_keys_split[0].startswith(
                    cmd_split[0]
                ) and command_keys_split[1].startswith(cmd_split[1]):
                    flag += 1
                    match_cmd = i  # 多个匹配match_cmd被覆盖也没关系,最后也是输出unknown command
            if flag == 1:
                print(command_values[match_cmd])
            else:
                print("unknown command")
        else:
            print("unknown command")

    except:
        break

发表于 2022-06-03 21:18:11 回复(0)
import java.util.*;
public class Main{
    public static void main (String[] args) {
        String com1 = "reset";
        String[] res0 = {"reset what","unknown command"};
        String[] com21 = {"reset", "board", "reboot", "backplane"};
        String[] com22 = {"board", "add", "delete", "backplane", "abort"};
        String[] res = {"board fault", "where to add", "no board at all", 
                       "impossible", "install first", "unknown command"};
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.nextLine();
            String[] temp = str.split(" ");
            if (temp.length == 1) {
                boolean flag1 = true;
                if (temp[0].length() > com1.length())
                    flag1 = false;
                else if (com1.startsWith(temp[0]) == false)
                    flag1 = false;
                if (flag1) System.out.println(res0[0]);
                else System.out.println(res0[1]);
            } 
            else if (temp.length == 2){
                boolean flag1 = false;
                for (int i = 0; i < com21.length; i++){
                  if (temp[0].length() <= com21[i].length() && com21[i].startsWith(temp[0]) == true)
                      flag1 = true;
                }
                if (flag1 == false) System.out.println(res0[1]);
                else {
                    int rnum = -1;
                    int bnum = -1;
                    if (temp[0].charAt(0) == 'r'){
                        if (temp[0].length() >= 3 && temp[0].charAt(2) == 's')
                            rnum = 0;
                        else if (temp[0].length() >= 3 && temp[0].charAt(2) == 'b')
                            rnum = 1;
                    } 
                    else if (temp[0].charAt(0) == 'b'){
                        if (temp[0].length() >= 2 && temp[0].charAt(1) == 'o')
                            bnum = 0;
                        else if (temp[0].length() >= 2 && temp[0].charAt(1) == 'a')
                            bnum = 1;
                    }
                    boolean flag2 = false;
                    int num = com22.length - 1;
                    for (int i = 0; i < com22.length; i++){
                        if (temp[1].length() <= com22[i].length() && com22[i].startsWith(temp[1]) == true){
                            if (flag2 != true)
                                num = i;
                            flag2 = true;
                        }
                    }
                    if (flag2 == false) System.out.println(res0[1]);
                    else{
                        if ((num == 0 || num == 3) && (rnum == -1))
                            System.out.println(res0[1]);
                        else {
                            if ((num == 1 || num == 4) && (bnum == -1)) 
                                System.out.println(res0[1]);
                            else System.out.println(res[num]);
                        }
                    }
                }
            }
            else System.out.println(res0[1]);
        }
    }
}
偷鸡法。这种题TM也算简单题的话,我愿称其他简单题为脑瘫题。
这题核心应该是考察str.split()和str.startsWith(),但为了满足原本的命令集和执行输出,处理上很麻烦,而且为了处理简单会导致拓展性极差,就很迷惑
发表于 2021-12-02 18:21:18 回复(0)
题意先匹配第一关键字再匹配第二关键字容易误导,一起匹配就好了。
先判断第二关键字是否为空
#include <stdio.h>
#include <string.h>
#define SIZE 20

const char *result[7] = {
    "unknown command","reset what","board fault","where to add",
    "no board at all","impossible","install first"
};

int match(char *arr);

int main(void)
{
    char arr[SIZE+2];
    while(fgets(arr,SIZE+1,stdin)){
        if(arr[strlen(arr) - 1] == '\n') arr[strlen(arr) - 1] = '\0';
        printf("%s\n",result[match(arr)]);
    }
    return 0;
}

int match(char *arr)
{
    char *first,*second,*pt;
    int ans = 0;
    
    pt = arr;
    while(*pt != ' ' && *pt != '\0') pt++;
    if(*pt = ' ') *pt++ = '\0';
    first = arr;
    second = pt;
    
    if(*second == '\0'){
        if(strstr("reset",first)) ans = 1;
    }else{
        if(strstr("reset",first) && strstr("board",second)){
            if(strstr("reboot",first) && strstr("backplane",second)) ans = 0;
            else ans = 2;
        }else if(strstr("board",first) && strstr("add",second)){
            if(strstr("backplane",first) && strstr("abort",second)) ans = 0;
            else ans = 3;
        }else if(strstr("board",first) && strstr("delete",second)){
            ans = 4;
        }else if(strstr("reboot",first) && strstr("backplane",second)){
            ans = 5;
        }else if(strstr("backplane",first) && strstr("abort",second)){
            ans = 6;
        }
    }
    return ans;
}



发表于 2021-11-08 16:38:08 回复(0)
// c++的参考太少了,留个脚印
#include<bits/stdc++.h>
using namespace std;

int cmdlen[6] = {0, 1, 1, 1, 1, 1};

string cmd[6][2] = {
    {"reset"},
    {"reset", "board"},
    {"board", "add"},
    {"board", "delete"},
    {"reboot", "backplane"},
    {"backplane", "abort"}
};

string ans[7] = {
    "reset what", 
    "board fault",
    "where to add",
    "no board at all",
    "impossible",
    "install first",
    "unknown command"
};

void re(string & str) {
    if(str == "") return;
    int n = 0, m = 0, ll = 0, len = str.length();
    queue<int> qe;
    qe.push(0);
    qe.push(1);
    qe.push(2);
    qe.push(3);
    qe.push(4);
    qe.push(5);
    for (; ll < len; ll++, m++) {
        if(str[ll] == ' ') {
            n++;
            m = -1;
            continue;
        }
        int xh = qe.size();
        while(xh--){
            int t = qe.front();
            qe.pop();
            if (cmd[t][n][m] == str[ll]) {
                qe.push(t);
            }
        }
    }
    int xh = qe.size();
    while(xh--){
        int t = qe.front();
        qe.pop();
        if (cmdlen[t] == n) {
            qe.push(t);
        }
    }
    if(qe.size() != 1) {
        cout<< ans[6];
    } else {
        cout<< ans[qe.front()];
    }
    cout<<endl;
}

int main() {
    string str;
    while(getline(cin, str)) {
        re(str);
    }
}

发表于 2021-09-06 17:53:35 回复(0)
import sys

commands = {}
commands['reset'] = 'reset what'
commands['reset board'] = 'board fault'
commands['board add'] = 'where to add'
commands['board delete'] = 'no board at all'
commands['reboot backplane'] = 'impossible'
commands['backplane abort'] = 'install first'

def isMatch(myCommand, command):
    if command[:len(myCommand)].find(myCommand) != -1:
        return True
    else:
        return False

for myCommand in sys.stdin:
    myCommand = myCommand.strip()
    space = myCommand.count(' ')
    match = 0 #计量匹配了几次
    output = '' #存储输出
    if myCommand == '':
        output = ''
        match += 1
    elif space == 0 and isMatch(myCommand, 'reset'):
        output = commands['reset']
        match += 1
    elif space == 1:
        myCommand = myCommand.split(' ')
        for command in commands.keys():
            if command.find(' ') != -1:
                command = command.split(' ')
                if isMatch(myCommand[0], command[0]) and isMatch(myCommand[1], command[1]):
                    command = ' '.join(command)
                    output = commands[command]
                    match += 1
    if match == 1:
        print(output)
    else:
        print('unknown command')
        

发表于 2021-08-04 21:38:59 回复(0)
//经过调试后的代码,自测和提交都可通过
#include <iostream>
#include <string>
#include <sstream>
//把命令和执行的命令分别放到不同的string数组里面
//***tream 的方式,把输入的 string 与 命令里面的 字符串做匹配即可
using namespace std;
bool match(string str,string s)
{
    return str.find(s) == 0;
}

// void split(string str, string &s1, string &s2)
// {
//     int i = str.find(' ');
//     s1 = str.substr(0, i);
//     s2 = str.substr(i+1, str.size() - i - 1);
// }


int main()
{
    string cmd[6] = {"reset",       "reset board", "board add",     "board delete",      "reboot backplane", "backplane abort" };
    string res[7] = {"reset what",  "board fault", "where to add",  "no board at all",  "impossible",       "install first",    "unknown command" };
    string str;
    while (getline(cin, str)) {
        if (str.empty()) continue;
        string s1, s2;
        int resi = 6;
        stringstream ss(str);
        ss>>s1>>s2;
        if(s2.empty())
            resi = match(cmd[0],s1)?0:6;
        else
        {
            int flag = 0;
            for(int i = 1;i<6;i++)
            {
                string tmp1,tmp2;
                stringstream ss(cmd[i]);
                ss>>tmp1>>tmp2;
                if(match(tmp1,s1) && match(tmp2,s2))
                {
                    if(flag == 0)
                    {
                        flag = 1;
                        resi = i;
                    }else
                    {
                        resi = 6;
                        break;
                    }
                }
            }
        }
        cout<<res[resi]<<endl;
    }
    return 0;
}//学习了

发表于 2021-08-03 16:32:35 回复(1)
Java使用matches那不是直接调库吗?分享给大家我的解法🤣
import java.util.*;
import java.io.*;
public class Main {
    static HashMap<String, String> maps = new HashMap<>();
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        maps.put("reset","reset what");
        maps.put("reset board","board fault");
        maps.put("board add","where to add");
        maps.put("board delete","no board at all");
        maps.put("reboot backplane","impossible");
        maps.put("backplane abort","install first");
        while ((str = br.readLine()) != null) {
            System.out.println(helper(str));
        }
    }
    public static String helper(String s) {
        String[] strs = s.split(" ");
        String ret = "unknown command";
        if (s == " ") {
            return ret;
        }
        int n = strs.length;
        if (n == 1) {
            // 输入一个字符串
            String cur = strs[0];
            if ("reset".contains(cur)) {
                ret = maps.get("reset");
            }
        } else if (n == 2) {
            // 输入两个字符串
            String first = strs[0];
            String second = strs[1];
            Set<String> keys = maps.keySet();
            int flag = 0;
            Iterator<String> iterator = keys.iterator();
            while(iterator.hasNext()) {
                String key = iterator.next();
                if (!key.equals("reset")) {
                    // 两个关键字
                    String[] key_set = key.split(" ");
                    if (key_set[0].indexOf(first) == 0 && !first.equals(second)) {
                        if (key_set[1].indexOf(second) == 0  && !first.equals(second)) {
                            if (ret.equals("unknown command")) {
                                ret = maps.get(key);
                            } else {
                                ret = "unknown command";
                                break;
                            }
                            
                        }
                    }
                }
            }
        } 
        return ret;
    }
}


发表于 2021-07-17 22:29:25 回复(0)
还没看完输入简化规则,居然提交过了。。。。。
s={'reset':'reset what','reset board':'board fault','board add':'where to add','board delete':'no board at all','reboot backplane':'impossible','backplane abort':'install first','board delete':'no board at all'}
while True:
    try:
        a=input()
        if a in s.keys():
            print(s[a])
        else:
            print('unknown command')
    except:
        break

发表于 2021-06-26 13:29:12 回复(1)
#include <iostream>
#include <map>
#include <vector>
using namespace std;

int main() 
{
    map<string,string> c***p;
	c***p["reset"] = "reset what";
	c***p["reset board"] = "board fault";
	c***p["board add"] = "where to add";
	c***p["board delete"] = "no board at all";
	c***p["reboot backplane"] = "impossible";
	c***p["backplane abort"] = "install first";

	string scmd;
	while(getline(cin,scmd))
	{
		vector<string> cmd_vec;
		string scmd1;
		string scmd2;
		int ipos = scmd.find(' ');
		if (string::npos == ipos)
		{
			scmd1 = scmd;
			cmd_vec.push_back(scmd1);
		}
		else
		{
			scmd1 = scmd.substr(0,ipos);
			scmd2 = scmd.substr(ipos+1,scmd.size()-ipos-1);
			cmd_vec.push_back(scmd1);
			cmd_vec.push_back(scmd2);
		}

		if (1==cmd_vec.size())
		{			
			vector<string> temp_vec;
			for (map<string,string>::iterator iter = c***p.begin();
				iter != c***p.end(); iter++)
			{
				if (iter->first.find(scmd1) != string::npos)
				{
					temp_vec.push_back(iter->first);
				}
			}

			bool bfind = false;
			for (int i=0;i<temp_vec.size();i++)
			{				
				if (temp_vec[i].find(' ')==string::npos)
				{
					bfind = true;
					cout << c***p[temp_vec[i]] <<endl;
				}
			}

			if (!bfind)
			{
				cout << "unknown command" <<endl;
			}

		}
		else
		{

			vector<string> temp_vec;
			for (map<string,string>::iterator iter = c***p.begin();
				iter != c***p.end(); iter++)
			{
				if (iter->first.find(' ') == string::npos)
				{
					continue;
				}
				int ipos = iter->first.find(' ');
				string scomp1 = iter->first.substr(0,ipos);
				string scomp2 = iter->first.substr(ipos+1,iter->first.size()-ipos-1);

				if (scomp1.find(scmd1) == string::npos)
				{
					continue;
				}
				if (scomp2.find(scmd2) == string::npos)
				{
					continue;
				}

				temp_vec.push_back(iter->first);
			}

			if (1==temp_vec.size())
			{
				cout << c***p[temp_vec[0]] <<endl;
			}
			else
			{
				cout << "unknown command" <<endl;
			}

		}

	}
    
    return 0;

}

发表于 2021-04-16 23:04:38 回复(0)
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
    string c;
    string list[6][3]={{"reset"},{"reset","board","board fault"},
                       {"board","add","where to add"},{"board","delete","no board at all"},
                       {"reboot","backplane","impossible"},{"backplane","abort","install first"}};
    while(getline(cin,c))
    {
        if(c.find(' ')==c.npos) 
        {
            if(list[0][0].find(c)!=list[0][0].npos)
            {cout<<"reset what"<<endl;continue;}
            else {cout<<"unknown command"<<endl;continue;}
        }
        else if(c.size())
        {
            int num=0;int k;stringstream ss;string com[2];
            ss<<c;ss>>com[0]>>com[1];
            for(int a=1;a<6;a++)
            {
                if(list[a][0].find(com[0])!=list[a][0].npos&&list[a][1].find(com[1])!=list[a][0].npos)
                {k=a;num+=1;}
            }
            if(num!=1) {cout<<"unknown command"<<endl;}
            else {cout<<list[k][2]<<endl;}
        }
    }
    return 0;
}

发表于 2021-04-15 17:14:23 回复(0)
写了一堆if else😂
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String command;
        while((command = br.readLine()) != null){
            String[] words = command.trim().split(" ");
            if(words.length == 1){
                // 命令只有一个词就检查一下是不是reset命令
                if("reset".startsWith(words[0]))
                    System.out.println("reset what");
                else
                    System.out.println("unknown command");
            }else if(words.length == 2){
                if("reset".startsWith(words[0]) && "reboot".startsWith(words[0])){
                    if("board".startsWith(words[1]) && "backplane".startsWith(words[1])){
                        // 匹配命令不唯一,匹配失败
                        System.out.println("unknown command");
                    }else if("board".startsWith(words[1])){
                        // 匹配的是reset board
                        System.out.println("board fault");
                    }else if("backplane".startsWith(words[1])){
                        // 匹配的是reboot backplane
                        System.out.println("impossible");
                    }else
                        System.out.println("unknown command");
                }else if("reset".startsWith(words[0])){
                    if("board".startsWith(words[1]))
                        System.out.println("board fault");
                    else
                        System.out.println("unknown command");
                }else if("reboot".startsWith(words[0])){
                    if("backplane".startsWith(words[1]))
                        System.out.println("impossible");
                    else
                        System.out.println("unknown command");
                }else if("board".startsWith(words[0]) && "backplane".startsWith(words[0])){
                    if("abort".startsWith(words[1]) && "add".startsWith(words[1])){
                        // 匹配命令不唯一,匹配失败
                        System.out.println("unknown command");
                    }else if("delete".startsWith(words[1])){
                        // 匹配的是board delete
                        System.out.println("no board at all");
                    }else if("abort".startsWith(words[1])){
                        // 匹配的是backplane abort
                        System.out.println("install first");
                    }else if("add".startsWith(words[1])){
                        // 匹配的是board add
                        System.out.println("where to add");
                    }else
                        System.out.println("unknown command");
                }else if("board".startsWith(words[0])){
                    if("add".startsWith(words[1]))
                        System.out.println("where to add");
                    else if("delete".startsWith(words[1]))
                        System.out.println("no board at all");
                    else
                        System.out.println("unknown command");
                }else if("backplane".startsWith(words[0])){
                    if("abort".startsWith(words[1]))
                        System.out.println("install first");
                    else
                        System.out.println("unknown command");
                }else
                    System.out.println("unknown command");
            }else{
                // 命令超过两个词肯定是未知命令
                System.out.println("unknown command");
            }
        }
    }
}
编辑于 2021-03-26 09:56:41 回复(0)
#include<stdio.h>
#include<string.h>
#define N 1024
int main()
{   char str[N];
    while(gets(str)){
        
    int n=strlen(str);
    int i;
    int flag;
    flag=0;
    for(i=0;i<n;i++)
    {if (str[i]==' ') flag=1;}
       if(flag==0)  
          {if(str[0]=='r') printf("reset what\n");}         
       if(flag==1) 
       {
           for(i=0;i<n;i++)
    { 
       if(str[i]==' ')
      {
         if(str[0]=='b'&& str[i+1]=='d') {printf("no board at all\n");break;} 
         else if(str[0]=='b'&&str[1]=='o'&&str[i+1]=='a') {printf("where to add\n");break;}
         else if(str[0]=='b'&&str[1]=='a'&&str[i+1]=='a') {printf("install first\n");break;}
         else if(str[0]=='r' && str[i+1]=='b'&&(str[i+2]=='a'||str[2]=='b') ) {printf("impossible\n");break;}
         else if(str[0]=='r' && str[i+1]=='b'&&(str[i+2]=='o'||str[2]=='s') ) {printf("board fault\n");break;}
         else printf("unknown command\n");
      }
      } 
  
       }
  }      
    return 0;
}
这里没人上C, 我就上一个C语言版本的,简单易懂
发表于 2021-03-11 06:32:39 回复(0)
dic = {'reset': 'reset what',
       'reset board': 'board fault',
       'board add': 'where to add',
       'board delete': 'no board at all',
       'reboot backplane': 'impossible',
       'backplane abort': 'install first'}
while True:
    try:
        com = input().strip()
        # 若输入的命令是完整命令,则直接输出执行结果
        if com in dic:
            print(dic[com])
        else:  # 输入的是命令的简化形式
            simcom_list = com.split(' ')
            if len(simcom_list) == 1:  # 输入的是一字串,只能匹配一个关键字的命令(本题的:reset命令)
                if 'reset'.startswith(simcom_list[0]):
                    print("reset what")
                else:
                    print("unknown command")
            elif len(simcom_list) == 2:  # 输入的是两字串,只能匹配两个关键字的命令
                match = []  # 用于存放可以匹配的完整命令
                for k in dic:  # 字典迭代取出的是键,即为完整命令
                    if ' ' in k:  # 排除掉一个关键字的命令
                        totalcom_list = k.split(' ')
                        # 若匹配成功第一个关键字,且匹配成功第二个关键字
                        if totalcom_list[0].startswith(simcom_list[0]) and totalcom_list[1].startswith(simcom_list[1]):
                            match.append(k)
                if len(match) == 1:
                    print(dic[match[0]])
                else:
                    print("unknown command")
            else:  # 输入的是三字串或者更多字串
                print("unknown command")
    except:
        break

发表于 2021-01-05 20:46:10 回复(0)
适应扩展的情况,比如提供多个单一字符串的命令时,代码同样适用。
while True:
    try:
        command = input().split()
        dic1 = {'reset':'reset what', 'unk':'unknown command'}
        dic2 = {'reset board':'board fault', 'board add':'where to add', 
               'board delete':'no board at all', 'reboot backplane':'impossible', 
               'backplane abort':'install first'}
        if len(command) is 1:
            tag = False
            for k in dic1.keys():
                if command[0] == k[:len(command[0])]:
                    print(dic1[k])
                    tag = True
            if not tag:
                print(dic1['unk'])
        elif len(command) is 2:
            tag = False
            for k in dic2.keys():
                if command[0] == k[:len(command[0])] and command[1] == k.split()[1][:len(command[1])]:
                    print(dic2[k])
                    tag = True
            if not tag:
                print(dic1['unk'])
        else:
            print(dic1['unk'])
    except EOFError:
        break


发表于 2020-10-01 14:22:45 回复(1)
标准C语言,用了memcpy和strcmp函数,120行,淦!但是我的程序有bug,没有考虑输入b  r匹配多个的情况,但是居然给过了.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int  main (void)
{
    char a1[20]="reset";
    char a2[20]="board";
    char a3[20]="add";
    char a4[20]="delete";
    char a5[20]="reboot";
    char a6[20]="backplane";
    char a7[20]="abort";
    char b[20],c[20],d[20],e[20];
    char comd[20];
    int i=0;
    int j=0;
    while (gets(comd)!=NULL)
    {

        int lon=0;
        int flag=0;
        lon=strlen(comd);
        for (i=0;i<lon;i++)
        {
            if (comd[i]==' ')
            {
                flag=1;
                break;
            }
        }

        j=lon-i-1;
        if(flag==0)

		{
	        memcpy(b,a1,i*sizeof(char));
	        b[i]='\0';
			if (strcmp(comd,b)==0)
			{
			printf("reset what\r\n");
			}
			else 	printf("unknown command\r\n");
		}
		else
		{
			if(comd[0]=='r' && comd[i+1]=='b')   /*两端首字母为r  b*/
			{
			 memcpy(b,a1,i*sizeof(char));
			 memcpy(c,comd,i*sizeof(char));
			 b[i]='\0';
			 c[i]='\0';
			 	if 	(strcmp(b,c)==0)           /*如果第一个匹配reset*/
			 	{
			     memcpy(d ,a2,j*sizeof(char));
			 	 memcpy(e,comd+i+1,j*sizeof(char));
			     d[j]='\0';
			     e[j]='\0';

				 if (strcmp(d,e)==0)  printf("board fault\r\n");   /*第二个匹配board*/
				 else printf("unknown command\r\n");   /*第二个不匹配*/
				}
				else                               /*如果第一个不是reset,那是不是reboot*/
				{
				 memcpy(b,a5,i*sizeof(char));
				 memcpy(c,comd,i*sizeof(char));
				 b[i]='\0';
				 c[i]='\0';
				 if (strcmp(b,c)==0)                 /*如果第一个是reboot*/
				 {
				 memcpy(d ,a6,j*sizeof(char));
			 	 memcpy(e,comd+i+1,j*sizeof(char));
			     d[j]='\0';
			     e[j]='\0';
			     if (strcmp(d,e)==0)  printf("impossible\r\n");  /*第二个是backplane,输出*/
			     else printf("unknown command\r\n");
				 }
				 else printf("unknown command\r\n");
				}

			}
			else if (comd[0]=='b')    /*如果第一个是b*/
			{
			 memcpy(b,a2,i*sizeof(char));
			 memcpy(c,comd,i*sizeof(char));
			 b[i]='\0';
			 c[i]='\0';
			 if (strcmp(b,c)==0)    /*如果是board*/
			 	{
			     memcpy(d ,a3,j*sizeof(char));
			 	 memcpy(e,comd+i+1,j*sizeof(char));
			     d[j]='\0';
			     e[j]='\0';
				  if (strcmp(d,e)==0)  printf("where to add\r\n"); 	 /*第二个是add*/
				  else
				  {
				   memcpy(d,a4,j*sizeof(char));
				   if (strcmp(d,e)==0)   printf("no board at all\r\n");
				  else  printf("unknown command\r\n");
				  }

				}
			 else                /*不是board,是backplan?*/
			 {
			 memcpy(b,a6,i*sizeof(char));
			   if 	(strcmp(b,c)==0)
			   {
			     memcpy(d ,a7,j*sizeof(char));
			 	 memcpy(e,comd+i+1,j*sizeof(char));
			     d[i]='\0';
			     e[i]='\0';
				 if (strcmp(d,e)==0)  printf("install first\r\n");   /*第二个是 abort*/
				 else  printf("unknown command\r\n");
			   }
			   else  printf("unknown command\r\n");   /*既不是board 也不是  backplane*/

			 }
			}
			else printf("unknown command\r\n");

		}
   }

}




发表于 2020-08-21 18:55:31 回复(0)