LeetCode 211. Add and Search Word - Data structure design(字典树)

Posted Shendu.cc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 211. Add and Search Word - Data structure design(字典树)相关的知识,希望对你有一定的参考价值。

题目

字典树。

class WordDictionary {
public:
    int map[100005][26];
    int tag[100005];
    int num;
    /** Initialize your data structure here. */
    WordDictionary() {
        
        memset(map,0,sizeof(map));
        memset(tag,0,sizeof(tag));
        num=0;
        
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        
        Add(word,0,0);
        
    }
    
    void Add(string word,int i,int pos)
    {
        if(i==word.length())
        {
            tag[pos]=1;
            return;
        }
            
        if(map[pos][word[i]-'a']==0)
        {
            map[pos][word[i]-'a']=++num;
        }
            
        Add(word,i+1,map[pos][word[i]-'a']);
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    bool search(string word) {
        
        return  SearchWord(word,0,0);
        
    }
    
    bool SearchWord(string word,int i,int pos)
    {
        if(i==word.length())
        {
            if(tag[pos]==1)
            return true;
            else
            return false;
        }
        
        if(word[i]=='.')
        {
            for(int j=0;j<26;j++)
            {
                if(map[pos][j]!=0)
                {
                   bool ans = SearchWord(word,i+1,map[pos][j]);
                   if(ans==true)
                       return true;
                }
            }
            return false;
        }
        else
        {
            if(map[pos][word[i]-'a']==0)
            {
                return false;
            }
            else
            {
               return SearchWord(word,i+1,map[pos][word[i]-'a']);
            }
        }
      
    }
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */

以上是关于LeetCode 211. Add and Search Word - Data structure design(字典树)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-211 Add and Search Word - Data structure design

leetcode 211. Add and Search Word - Data structure design

Leetcode 211: Add and Search Word - Data structure design

[LeetCode] 211. Add and Search Word - Data structure design Java

[leetcode trie]211. Add and Search Word - Data structure design

LeetCode 211. Add and Search Word - Data structure design(字典树)