原题链接:676. 实现一个魔法字典
solution:
哈希+单词比较
class MagicDictionary {
public:
unordered_map<string, int> dict;
MagicDictionary() {
}
void buildDict(vector<string> dictionary) {
for(auto &x : dictionary) dict[x] = x.size(); //哈希表存储单词和长度
}
bool search(string searchWord) {
int n = searchWord.size();
for(auto &[d, cnt] : dict) {
int diff = 0; //储存不相等字母个数
if(n != cnt) continue;
for(int i = 0;i < n;i++) {
if(searchWord[i] != d[i]) diff++;
if(diff > 1) break;
}
if(diff == 1) return true;
}
return false;
}
};