题解 | #配置文件恢复#

配置文件恢复

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

C++版本
个人认为将单词命令和双词命令分开来处理比较容易理解。
将两种命令分别存入两个数组,利用pair形式能够轻易获取其执行结果。
对于输入的每个命令,试图将其拆分为两部分。如果是一个词,那么直接进入one数组里面匹配。
如果是两个词,则注意Word2应该以空格为起始点,这样能限制Word2这个子串是独一无二的。例如"b"可能会匹配"reboot"里面的b,但是" b"只能匹配" backplane"中的b。
由于两个词的命令可能会匹配到多个,所以使用count计数,只有count为1的情况才算匹配成功,其他情况都是失败的

#include
#include
#include
using namespace std;
int main(){
    vector> one;
    one.push_back(make_pair("reset", "reset what"));
    vector> two;
    two.push_back(make_pair("reset board", "board fault"));
    two.push_back(make_pair("board add", "where to add"));
    two.push_back(make_pair("board delete", "no board at all"));
    two.push_back(make_pair("reboot backplane", "impossible"));
    two.push_back(make_pair("backplane abort", "install first"));
    vector result;
    string str, word1, word2;
    while(getline(cin, str)){
        bool single = true;
        word1 = "";
        word2 = "";
        for(auto c : str){
            if(c==' '){
                single = false;
            }
            if(single) word1 += c;
            else word2 += c;
        }
        if(single){
            for(auto item : one){
                if(item.first.find(word1)==0) result.push_back(item.second);
                else result.push_back("unknown command");
            }
        }
        else{
            int count = 0;
            string temp = "";
            for(auto item : two){
                int pos1 = item.first.find(word1);
                int pos2 = item.first.find(word2);
                if(pos1==0 && pos2!=string::npos){
                    count++;
                    temp = item.second;
                }
            }
            if(count==1) result.push_back(temp);
            else result.push_back("unknown command");
        }
    }
    for(auto item : result) cout<<item<<endl;
}
#在线刷题#
全部评论

相关推荐

牛客ID:561366855:期望薪资多少?难以相信这简历找不到工作。说明二本电子信息专业想对口就业非常难。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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