题解 | #魔咒词典#
魔咒词典
http://www.nowcoder.com/practice/c6ca566fa3984fae916e6d7beae8ea7f
注意因为key和value都不会重复出现,所以可以将题目中描述的两个映射关系用一个映射实现
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<string, string> dictionary;
while (true) {
string s;
getline(cin, s);
if (s == "@END@") break;
int pos = s.find("]");
string key = s.substr(0, pos+1);
string value = s.substr(pos+2);
dictionary[key] = value;
dictionary[value] = key;
}
int M;
cin >> M;
getchar();
while (M--) {
string s;
getline(cin, s);
if (s[0] == '[') {
if (dictionary.find(s) != dictionary.end()) {
cout << dictionary[s] << endl;
}
else {
cout << "what?" << endl;
}
}
else {
if (dictionary.find(s) != dictionary.end()) {
string res = dictionary[s];
res = res.substr(1);
res.pop_back();
cout << res << endl;
}
else {
cout << "what?" << endl;
}
}
}
return 0;
}