211 添加与搜索单词

思路:前缀树,注意输入正则字符串的时候对’ . '的处理。

class Trie
{
public:
    bool is_end;
    Trie *next[26];
    Trie()
    {
        is_end = false;
        for(int i = 0; i < 26; ++i) next[i] = nullptr;
    }

    void insert(const string& word) // 前缀树的插入操作
    {
        Trie *t = this;
        for(auto c : word)
        {
            if(t->next[c - 'a'] == nullptr) t->next[c - 'a'] = new Trie();
            t = t->next[c - 'a'];
        }
        t->is_end = true;
    }

    bool search(const string &word, Trie *root)
    {
        Trie *t = root;
        for(int i = 0; i < word.size(); ++i)
        {
            if(word[i] == '.')
            {
                for(int j = 0; j < 26; ++j)
                {
                    if(t->next[j] != nullptr && search(word.substr(i + 1), t->next[j]))
                        return true;
                }
                return false; // next均为nullptr
            }
            else if(t->next[word[i] - 'a'] == nullptr) return false;
            else t = t->next[word[i] - 'a']; // 存在则往下搜索
        }
        return t->is_end; // 返回标记位
    }
};

class WordDictionary {
    Trie *root;
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new Trie();
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        root->insert(word);
    }
    
    /** 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 root->search(word, root);
    } 
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值