zoukankan      html  css  js  c++  java
  • 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);
     */
    
  • 相关阅读:
    Tornado输出和响应头
    sqlalchemy 学习(二)scoped session
    04:sqlalchemy操作数据库 不错
    sqlalchemy(二)高级用法
    红黑树
    Minimum Window Substring
    Max Points on a Line
    分治算法
    Maximum Subarray
    Word Break
  • 原文地址:https://www.cnblogs.com/dacc123/p/12311052.html
Copyright © 2011-2022 走看看