LeetCode第 211 题:添加与搜索单词 - 数据结构设计(C++)

211. 添加与搜索单词 - 数据结构设计 - 力扣(LeetCode)

两个操作,添加和搜索。

搜索的时候 '.'可以匹配任何字符。

其余的很像LeetCode第 208 题:实现Trie(前缀树)(C++)

但是这儿如果这个字符是 '.'的时候,需要特殊处理,需要遍历成员数组中的每一个位置,只要有一个位置可达终点,就返回true。

class WordDictionary {
public:
    struct TrieNode{
        bool isEnd = false;
        TrieNode* children[26] = {NULL};
    };

    WordDictionary() : root(new TrieNode) {}
    
    void addWord(string word) {
        auto p = root;
        for(int i = 0; i < word.size(); ++i){
            int idx = word[i] - 'a';
            if(p->children[idx] == NULL)    p->children[idx] = new TrieNode;
            p = p->children[idx];
        }
        p->isEnd = true;
    }
    
     bool search(string word) {
         return subSearch(root, word);
     }
     //从p开始,检索word
    bool subSearch(TrieNode *p, string word) {
        if(!p)  return false;        
        for(int i = 0; i < word.size(); ++i){
            if(word[i] == '.'){
                for(int j = 0; j < 26; ++j)
                    if(subSearch(p->children[j], word.substr(i+1))) return true;//至少有一个可达
                return false;
            }
            int idx = word[i] - 'a';
            if(p->children[idx] == NULL)    return false;
            p = p->children[idx];
        }
        return p->isEnd;
    }

private:
    TrieNode *root;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值