题解 | #配置文件恢复# 哈希
配置文件恢复
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; }