leetcode实现魔法字典

1.前缀树

使用前缀树构建字典,当search的每一个Word,

class TrieNode{
public:
   bool isWord;//是否是一个单词
   TrieNode *child[26];//定义孩子节点
   TrieNode(){
       isWord=false;
       memset(child,0,sizeof(child));
   }
   ~TrieNode(){
       for(int i=0;i<26;i++)
         if(child[i])
           delete child[i];
   }
};
class MagicDictionary {
    TrieNode *root;
    void insert(string &word)
    {
        TrieNode *p=root;
        for(int i=0;i<word.size();i++)
        {
            char c=word[i];
            if(p->child[c-'a']==NULL)
              p->child[c-'a']=new TrieNode();
            p=p->child[c-'a'];
        }
        p->isWord=true;
    }
    //flag标记是否使用了替换一个字母的机会,如果替换一个字母之后能够匹配,则返回true
    bool subsearch(TrieNode *root,string word,int index,bool flag)
    {
       if(root==NULL)
          return false;
        if(word.size()==index)//搜索完毕
          return flag&&root->isWord;
        else
        {
            //继续搜索root的26个节点
            for(int i=0;i<26;i++)
            {
                if(root->child[i]!=NULL)
                {
                    if('a'+i==word[index])//成功匹配,搜索下一个字母
                    {
                       if(subsearch(root->child[i],word,index+1,flag))//在Index之后替换了字母且匹配成功
                          return true;
                    }
                    else if(flag==false&&subsearch(root->child[i],word,index+1,true))//若flag==false,则替换Index,匹配成功
                          return true;
                      
                }
            }
        }
        return false;
    }
public:
    /** Initialize your data structure here. */
    MagicDictionary() {
      root=new TrieNode();
    }
    
    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for(int i=0;i<dict.size();i++)
             insert(dict[i]);//插入
    }
    
    /** 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 subsearch(root,word,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);
 */
发布了191 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38196982/article/details/104868040