Lintcode---单词的添加与查找

设计一个包含下面两个操作的数据结构:addWord(word), search(word)

addWord(word)会在数据结构中添加一个单词。而search(word)则支持普通的单词查询或是只包含.a-z的简易正则表达式的查询。

一个 . 可以代表一个任何的字母。

 注意事项

你可以假设所有的单词都只包含小写字母 a-z。

样例
addWord("bad")
addWord("dad")
addWord("mad")
search("pad")  // return false
search("bad")  // return true
search(".ad")  // return true
search("b..")  // return true


思路:先定义字典树节点类,用以实现字典树;

        
         添加单词过程和之前的过程一模一样,在查找的时候,过程也类似,但要对‘.’字符进行特殊处理,这是问题的关键;
       
        因为字符为'.'的时候,一个 . 可以代表一个任何的字母,在这种情况下,使用递归比较好实现。


/*
思路:先定义字典树节点类,用以实现字典树;
         
        添加单词过程和之前的过程一模一样,在查找的时候,过程也类似,但要对‘.’字符进行特殊处理,这是问题的关键;
        
        因为字符为'.'的时候,一个 . 可以代表一个任何的字母,在这种情况下,使用递归比较好实现。
        

*/

//节点类的定义,注意构造函数对所有数据成员都进行初始化;

const int MAX_CHILD=26;
class TrieNode {
public:
    // Initialize your data structure here.
    int count;
    TrieNode* child[MAX_CHILD];
    TrieNode() {
        for(int i = 0; i < 26; i++)
            child[i] = NULL;
        count=0;
    }
};

class WordDictionary {
public:

    WordDictionary() {
        root = new TrieNode();
    }
    
    
    // Adds a word into the data structure.
    //添加单词过程和插入过程一模一样
    void addWord(string word) {
        // Write your code here
        
        if(root==NULL||word.size()==0){
            return;
        }
        
        int len=word.size();
        TrieNode* t=root;
        int i=0;
        
        while(i<len){
            if(t->child[word[i]-'a']==NULL){
                TrieNode* temp=new TrieNode();
                t->child[word[i]-'a']=temp;
                t=t->child[word[i]-'a'];
            }
            else{
                t=t->child[word[i]-'a'];
            }
            i++;
        }
        t->count=1;
    }

    // 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
        search(word, root, 0);
    }
    
    bool search(string &word, TrieNode *p, int i){
        if (i == word.size()){
            return p->count;
        }
        
        //当遇到字符为'.'的时候,一个 . 可以代表一个任何的字母;
        //这里用递归的方式判断输入字符串是否存在;
        
        if (word[i] == '.') {
            for (auto a : p->child) {
                if (a && search(word, a, i + 1)){
                    return true;
                }
            }
            return false;
        } 
        else {
            return p->child[word[i] - 'a'] && search(word, p->child[word[i] - 'a'], i + 1);
        }
    }
    
private:
    TrieNode *root;  
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
 
原文地址:https://www.cnblogs.com/Allen-rg/p/7135898.html