LeetCode676. 实现一个魔法字典
题目描述
本题目来自LeetCode上的『676. 实现一个魔法字典』
设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
实现 MagicDictionary 类:
MagicDictionary()初始化对象void buildDict(String[] dictionary)使用字符串数组dictionary设定该数据结构,dictionary中的字符串互不相同bool search(String searchWord)给定一个字符串searchWord,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回true;否则,返回false。
示例1:
输入
[“MagicDictionary”, “buildDict”, “search”, “search”, “search”, “search”]
[[], [[“hello”, “leetcode”]], [“hello”], [“hhllo”], [“hell”], [“leetcoded”]]
输出
[null, null, false, true, false, false]解释
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict([“hello”, “leetcode”]);
magicDictionary.search(“hello”); // 返回 False
magicDictionary.search(“hhllo”); // 将第二个 ‘h’ 替换为 ‘e’ 可以匹配 “hello” ,所以返回 True
magicDictionary.search(“hell”); // 返回 False
magicDictionary.search(“leetcoded”); // 返回 False
提示
1 <= dictionary.length <= 1001 <= dictionary[i].length <= 100dictionary[i]仅由小写英文字母组成dictionary中的所有字符串 互不相同1 <= searchWord.length <= 100searchWord仅由小写英文字母组成buildDict仅在search之前调用一次- 最多调用
100次search
题解
将 dictionary 中所有单词存入字典树中,对于每一个待查的单词,使用深搜进行匹配,具体如下:
- 设置变量
cnt记录不一样的字符的个数。 - 当
cnt > 1时,表示至少有两个字符不一样,终止搜索。 - 遍历当前结点的每一个子结点,在子结点存在的前提下,字符相同,则
cnt不变,搜索下一个字符;字符不同,cnt + 1,搜索下一个字符。 - 当遍历到待查单词的结尾时,如果当前结点的
isEnd = true且cnt = 1,则返回true。
代码
class Trie {
private:
bool isEnd;
vector<Trie*> children;
public:
Trie() : children(26), isEnd(false) {}
void insert(const string& word) {
Trie* node = this;
for (const auto& ch: word) {
int idx = ch - 'a';
if (node->children[idx] == nullptr) {
node->children[idx] = new Trie();
}
node = node->children[idx];
}
node->isEnd = true;
}
bool search(const string& word, int idx, int cnt) {
if (cnt > 1) return false;
Trie* node = this;
if (idx == word.size()) return node->isEnd && cnt == 1;
for (int i = 0; i < 26; ++i) {
if (node->children[i] == nullptr) {
continue;
}
int t = word[idx] - 'a' == i ? cnt : cnt + 1;
if (node->children[i]->search(word, idx + 1, t)) {
return true;
}
}
return false;
}
};
class MagicDictionary {
private:
Trie* root;
public:
MagicDictionary() {
root = new Trie();
}
void buildDict(vector<string> dictionary) {
for (const auto& s: dictionary) {
root->insert(s);
}
}
bool search(string searchWord) {
return root->search(searchWord, 0, 0);
}
};