题解 | #配置文件恢复# 哈希

配置文件恢复

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

#include <iostream>
#include <unordered_map>
#include <utility>
#include <sstream>

using namespace std;

struct keys {
    string first;
    string second;
    keys() {
        first = "";
        second = "";
    }
    keys(string f, string s) {
        first = std::move(f);
        second = std::move(s);
    }
    bool operator==(const keys& p) const {
        return first == p.first && second == p.second;
    }
};

struct hash_keys {
    size_t operator()(const keys& p) const {
        return hash<string>()(p.first) ^ hash<string>()(p.second);
    }
};
unordered_map<keys, string, hash_keys> map {
    {{"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"}
};

bool str_match(string pattern, string source) {
    if (pattern == "" && source == "") {
        return true;
    } else if (source == "" || pattern == "") {
        return false;
    }
    int i = 0;
    while (i < pattern.size()) {
        if (pattern[i] != source[i]) {
            return false;
        }
        i++;
    }
    return true;
}

void match(string first, string second) {
    int match_cnt = 0;
    string res;
    for (const auto& entry : map) {
        string p_first = entry.first.first;
        string p_second = entry.first.second;
        if (str_match(first, p_first) 
            && str_match(second, p_second)) {
            ++match_cnt;
            res = entry.second;
        }
    }
    if (match_cnt == 1) {
        cout << res << endl;
    } else {
        cout << "unknown command" << endl;
    }
}

int main() {
    string line;
    string first;
    string second;
    while (getline(cin, line)) {
        if (line.find(' ') == string::npos) {
            first = line;
            second = "";
        } else {
            stringstream ss(line);
            ss >> first;
            ss >> second;
        }
        match(first, second);
    }
    return 0;
}

全部评论

相关推荐

Bug压路:老哥看得出来你是想多展示一些项目,但好像一般最多两个就够了😂页数一般一页,多的也就2页;这些项目应该是比较同质化的,和评论区其他大佬一样,我也觉得应该展示一些最拿手的(质量>数量)😁😁😁专业技能部分也可以稍微精简一些
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务