Leetcode 676. 实现一个魔法字典 C++

本文介绍如何使用字典树和深度优先搜索解决LeetCode 676题,实现一个魔法字典,包含buildDict和search方法。通过构建字典树并进行DFS,判断给定单词在一次字母替换后是否存在于字典中。

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

注意:

  1. 你可以假设所有输入都是小写字母 a-z。
  2. 为了便于竞赛,测试所用的数据量很小。你可以在竞赛结束后,考虑更高效的算法。
  3. 请记住重置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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值