构造一个单词查找树,支持以下两个操作的数据结构: 添加和搜索,只包含字母a-z或.。

本题源自 leetcode  211

--------------------------------------------------------------------------------

思路:用一个单词查找树结构 Trie.添加单词就是把这个单词添加到字典中,然后a设置-z子串。

搜索,就在trie中搜素,如果不是正则匹配,就在其子串中搜素,否则递归匹配。

代码:

class Trie{
    public:
        bool isKey;
        Trie* children[26];
        Trie(){
            isKey = false;
            memset(children,NULL,sizeof(Trie*) * 26);
        }
    };
class WordDictionary {
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new Trie();
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        Trie * node = root;
        for(char c : word){
            if(!node->children[c - 'a'])
                node->children[c - 'a'] = new Trie();
            node = node->children[c - 'a'];
        }
        node->isKey = 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) {
        return query(word.c_str(),root);
    }
private:
    Trie* root;
    bool query(const char* word,Trie* root){
        Trie* node = root;
        for(int i = 0; word[i]; i++){
            if(node && word[i] != '.'){
                node = node->children[word[i] - 'a'];
            }else if(node && word[i] == '.'){
                Trie* tmp = node;
                for(int j = 0; j < 26; j++){
                    node = tmp->children[j];
                    if(query(word + i + 1, node))
                        return true;
                }
            }
            else 
                break;
        }
        return node && node->isKey;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值