Leetcode 676. Implement Magic Dictionary
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the MagicDictionary
class:
MagicDictionary()
: Initializes the object.void buildDict(vector<string> dictionary)
: Builds a dictionary through a list of words.bool search(string searchWord)
: Returns true if you can change exactly one character in searchWord
to match any word in the dictionary, otherwise returns false.dictionary
contain duplicate words?buildDict
overwrite the existing dictionary or extend it?Assuming the dictionary contains only unique words composed of lowercase English letters, and buildDict
overwrites the existing dictionary.
searchWord
into a dictionary word by changing exactly one character:
searchWord
, compare the words character by character.searchWord
when searching.#include <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
using namespace std;
class MagicDictionary {
private:
unordered_map<int, unordered_set<string>> dictionaryMap;
public:
MagicDictionary() {
}
void buildDict(vector<string> dictionary) {
dictionaryMap.clear();
for (const string& word : dictionary) {
dictionaryMap[word.size()].insert(word);
}
}
bool search(string searchWord) {
int wordLength = searchWord.size();
if (dictionaryMap.find(wordLength) == dictionaryMap.end()) {
return false;
}
for (const string& word : dictionaryMap[wordLength]) {
int diffCount = 0;
for (int i = 0; i < wordLength; ++i) {
if (searchWord[i] != word[i]) {
++diffCount;
}
if (diffCount > 1) {
break;
}
}
if (diffCount == 1) {
return true;
}
}
return false;
}
};
searchWord
and k is the number of words in the dictionary that have the same length as searchWord
(since we check each word of the same length character by character).This approach ensures efficient look-up by leveraging a hashmap and reduces unnecessary comparisons by focusing only on words of the same length.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?