题解 | #配置文件恢复#

配置文件恢复

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

#include<iostream>
#include<vector>
#include<string.h>
using namespace std;

int main(){
    string input;
    vector<pair<string,string>> commands = {{"reset",""},
                                            {"reset","board"},
                                            {"board","add"},
                                            {"board","delete"},
                                            {"reboot","backplane"},
                                            {"backplane","abort"}
                                           };
    vector<string> execs = {{"reset what"},
                            {"board fault"},
                            {"where to add"},
                            {"no board at all"},
                            {"impossible"},
                            {"install first"}
                           };
    while(getline(cin,input)){
        string cmd_input1 = input;
        string cmd_input2 = "";
        string res = "unknown command";
        int cnt= 0;

        // 分割input
        for(int i = 0 ; i < input.size(); i++){
            if(input[i] == ' '){
                cmd_input1 = input.substr(0,i);
                cmd_input2 = input.substr(i+1);
            }
        }

//         cout << cmd_input1 << "," << cmd_input2 << endl;

        // 遍历指令集
        for(auto iter = commands.begin();iter!=commands.end();iter++){
            bool flag1 = false;
            bool flag2 = false;
            string cmd1 = iter->first;
            string cmd2 = iter->second;

//             cout << "当前指令:" << commands[iter-commands.begin()].first << ',' << commands[iter-commands.begin()].second<< endl;

            // 验证cmd1是否匹配
            int index1 = cmd1.find(cmd_input1);
            if( index1 )
                continue;

            // 验证cmd2是否匹配
            int index2 = -1;
            if(cmd_input2!=""){
                index2 = cmd2.find(cmd_input2);
            }
            else if( cmd_input2 == "" && cmd2 == ""){
                index2 = 0;
            }
            else{
                index2 = -1;
            }

//             cout << "index2: "<<index2 << endl;

            // 验证指令是否有效
            if( !index1 && !index2 ){
//                 cout <<"当前指令有效,输出执行任务:" <<execs[iter - commands.begin()]<< endl;
                cnt++;
                // 验证是否唯一匹配
                if( cnt == 1 )
                    res = execs[iter - commands.begin()];
                else
                    res = "unknown command";
            }

        }
        cout << res << endl;

    }
}
全部评论

相关推荐

伟大的烤冷面被普调:暨大✌🏻就是强
点赞 评论 收藏
分享
10-05 11:11
海南大学 Java
投票
理想江南137:感觉挺真诚的 感觉可以试一试
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务