• LeetCode 211. Add and Search Word


    题目

    字典树。

    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);
     */
    
  • 相关阅读:
    Javascript优化
    网页设计单页和多页的选择
    让404页面变得更加实用
    优秀的主页设计
    CSS常见布局解决方案
    前端极限性能优化
    记一次项目实训心得经验
    部署windows2008虚拟机
    httprunner学习总结
    意见汇总
  • 原文地址:https://www.cnblogs.com/dacc123/p/12311052.html
Copyright © 2020-2023  润新知