Leetcode 676. 实现一个魔法字典
题目
实现一个带有buildDict, 以及 search方法的魔法字典。
对于buildDict方法,你将被给定一串不重复的单词来构建一个字典。
对于search方法,你将被给定一个单词,并且判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
示例:
Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False
注意:
- 你可以假设所有输入都是小写字母 a-z。
- 为了便于竞赛,测试所用的数据量很小。你可以在竞赛结束后,考虑更高效的算法。
- 请记住重置MagicDictionary类中声明的类变量,因为静态/类变量会在多个测试用例中保留。 请参阅这里了解更多详情。
题解
字典树+dfs
根据字典建立字典树。然后根据当前单词进行dfs,期间要进行1个字母的修改。详细过程见代码
代码
class MagicDictionary {
public:
struct Tree{
bool isWord;
Tree* next[26];
Tree(){
for(int i=0; i<26; i++)
next[i] = NULL;
isWord = false;
}
};
Tree* root;
/** Initialize your data structure here. */
MagicDictionary() {
root = new Tree();
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) { //建立字典树
int n = dict.size();
Tree* now;
for(int i=0; i<n; i++){
now = root;
for(int j=0; j<dict[i].length(); j++){
if(now->next[dict[i][j]-'a'] == NULL){
Tree* newT = new Tree();
now->next[dict[i][j]-'a'] = newT;
}
now = now->next[dict[i][j]-'a'];
}
now->isWord = true;
}
}
bool dfs(string word,Tree* now,int x,bool flag){ //flag表明是否修改了字母
if(x==word.length()-1){
if(flag) return now->next[word[x]-'a']!=NULL && now->next[word[x]-'a']->isWord; //已经修改过一个字母,只需要看当前表示的是不是单词
for(int i=0; i<26; i++){ //之前没有发生修改,因此修改最后一个字母
if(word[x]-'a'==i || now->next[i]==NULL) continue;
if(now->next[i]->isWord){
return true;
}
}
return false;
}else if(flag){ //发生修改,就不允许再修改字母
if(now->next[word[x]-'a'] == NULL) return false;
if(dfs(word,now->next[word[x]-'a'],x+1,flag)) return true;
}else{
if(now->next[word[x]-'a']){ //不修改当前字母
if(dfs(word,now->next[word[x]-'a'],x+1,flag)) return true;
}
for(int i=0; i<26; i++){ //修改当前字母
if(word[x]-'a'==i || now->next[i]==NULL) continue;
if(dfs(word,now->next[i],x+1,true)) return true;
}
}
return false;
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
return dfs(word,root,0,false);
}
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dict);
* bool param_2 = obj->search(word);
*/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-magic-dictionary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本文介绍如何使用字典树和深度优先搜索解决LeetCode 676题,实现一个魔法字典,包含buildDict和search方法。通过构建字典树并进行DFS,判断给定单词在一次字母替换后是否存在于字典中。

844

被折叠的 条评论
为什么被折叠?



