码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-15 13:53:46      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:har   HERE   i+1   int   nta   represent   The   class   new   

题目

字典树。

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(字典树)

标签:har   HERE   i+1   int   nta   represent   The   class   new   

原文地址:https://www.cnblogs.com/dacc123/p/12311052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!