【leetcode】211. Add and Search Word - Data structure design

题目:
在这里插入图片描述


思路:
数据结构与【leetcode】208. Implement Trie (Prefix Tree)是一样的,只是search函数从迭代的方式改成了递归的方式,因为遇到字符“.”会涉及到回溯。

我又对此数据结构的存储细节进行了剖析,以“dad”为例,其的存储结构如下图:
在这里插入图片描述


代码实现:

class TrieNode{
public:
    TrieNode *child[26];
    TrieNode():isWord(false){
        for (auto &a : child){
            a = nullptr;
        }
    }
    bool isWord; // 如果此节点最后一个字符,则说明到此为止是一个完整的单词。
};

class WordDictionary {
private:
    TrieNode *root;    
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new TrieNode();
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        TrieNode *p = root;
        for (auto &c : word){
            int i = c - 'a';
            if (p->child[i] == nullptr){
                p->child[i] = new TrieNode();
            }
            p = p->child[i];
        }
        p->isWord = 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 f(word, 0, root);
    }
    
    bool f(string &word, int w_i, TrieNode* p){
        if (w_i >= word.size()){
            return p->isWord;
        }
        
        if (word[w_i] == '.'){
            for (int i = 0; i < 26; ++i){
                if (p->child[i]){
                    if (f(word, w_i+1, p->child[i])){
                        return true;
                    }
                }
            }
        }else{
            if (p->child[word[w_i]-'a'] == nullptr){
                return false;
            }
            return f(word, w_i+1, p->child[word[w_i]-'a']);
        }
        
        return false;
    }
    
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值