题解 | #配置文件恢复#

配置文件恢复

https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5?tpId=37&tqId=21289&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=

#include <iostream>
#include <locale>
#include <map>
#include <string>
#include <vector>
using namespace std;

// 匹配规则
map<vector<string>, string> rule = {
    {{"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"}
};

// keys 的值
vector<vector<string>> keys = {
    {"reset"},
    {"reset","board"},
    {"board","add"},
    {"board","delete"},
    {"reboot","backplane"},
    {"backplane","abort"}
};

// 实现mysplit()
vector<string> mySplit(string com){
    int left = 0;
    int right = 1;
    vector<string> ans;

    while(right < com.size()){
        if(com.at(right) == ' '){
            ans.push_back(com.substr(left, right - left));
            left = right + 1;
            right = left;
        }
        right += 1;
    }
    ans.push_back(com.substr(left, right - left));
    return ans;
}

// 根据com_list找到对应的value
string findCom(vector<string> com_list){
    int ans = 0;
    string com = "";
    // cout << com_list[0] << " " << com_list[1] << endl;
    
    for(vector<string> key : keys){
        
        if(key.size() < 2){
            continue;
        }
        // cout << key.at(0) << " " << key.at(1) << endl;
        if(key.at(0).substr(0, com_list.at(0).size()) == com_list.at(0)
            && 
            key.at(1).substr(0, com_list.at(1).size()) == com_list.at(1))
        {
            ans++;
            com = rule[key];  
        }
        
    }

    return (ans == 1) ? com : "unknown command";
}

// 通过 com 构造 comlist
string match(string com){
    vector<string> com_list = mySplit(com);
    // cout << com_list.size() << endl;

    if(com_list.size() == 1){
        if(keys[0][0].substr(0, com_list.at(0).size()) == com_list.at(0)){
            return "reset what";
        }else{
            return "unknown command";
        }
    }else if(com_list.size() == 2){
        return findCom(com_list);
    }
    return "unknown command";
}

int main() {
    string a;
    // cout << match("backplane abort");
    // cout << match("b addr");
    while (getline(cin, a)) { // 注意 while 处理多个 case
        // cout << a << endl;
        cout << match(a) << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
11-01 20:03
已编辑
门头沟学院 算法工程师
Amazarashi66:这种也是幸存者偏差了,拿不到这个价的才是大多数
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务