add-and-search-word

Design a data structure that supports the following two operations:

void addWord(word)

bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

样例

addWord("bad")

addWord("dad")

addWord("mad")

search("pad") -> false

search("bad") -> true

search(".ad") -> true

search("b..") -> true

注意

You may assume that all words are consist of lowercase letters a-z.

class WordDictionary {
public:
    struct TrieNode{
        bool has;
        TrieNode *child[26];
        TrieNode(){
            has=false;
            for(int i=0;i<26;i++){
                child[i]=NULL;
            }
        }
    };
    WordDictionary(){
        root=new TrieNode();
    }
    // Adds a word into the data structure.
    void addWord(string word) {
        // Write your code here
        int n=word.size();
        TrieNode* tmp=root;
        for(int i=0;i<n;i++){
            if(tmp->child[word[i]-'a']==NULL) tmp->child[word[i]-'a']=new TrieNode();
            tmp=tmp->child[word[i]-'a'];
        }
        tmp->has=true;
    }

    // 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) {
        // Write your code here
        return search(word,0,root);
        
    }
    bool search(string word,int i,TrieNode* aroot){
        if(i==word.size()){
            return aroot->has;
        }
        if(word[i]!='.'){
            if(aroot->child[word[i]-'a']==NULL) return false;
            else return search(word,i+1,aroot->child[word[i]-'a']);
        }else{
            for(int k=0;k<26;k++){
                if(aroot->child[k]&&search(word,i+1,aroot->child[k])) return true;
            }
            return false;
        }
        
    }
private:
    TrieNode* root;
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");


你可能感兴趣的:(add-and-search-word)