leetcode:211. 添加与搜索单词 - 数据结构设计

该博客主要介绍了LeetCode上的211题,即如何设计一个字典树来实现添加单词和搜索功能。其中,搜索功能因为特殊要求('.'代表任意字符)而略有复杂,需要遍历所有子节点。博客详细讲解了TrieNode类的实现以及搜索的深度优先搜索策略。
摘要由CSDN通过智能技术生成

题目来源

题目描述

在这里插入图片描述

题目解析

这道题是leetcode:208. Implement Trie (Prefix Tree) 实现字典树(前缀树)的衍生,唯一不同的是search需要重写一下,因为这道题里面.可以代替任意字符,所以一旦有了.,就要查找所有的子树,只要有一个返回true,整个search就返回true


class WordDictionary {
    class TrieNode {
    public:
        TrieNode () : children(26, nullptr), is_word(false){

        }
        ~TrieNode (){
            for(auto  it : children){
                delete it;
            }
        }

        std::vector<TrieNode  *> children;
        bool is_word;
    };
public:
    WordDictionary() {
        root = new TrieNode();
    }

    ~WordDictionary(){
        delete root;
    }

    void addWord(string word) {
        TrieNode *p = root;
        for(auto &a : word){
            int i = a - 'a';
            if(p->children[i] == NULL){
                p->children[i] = new TrieNode();
            }
            p = p->children[i];
        }
        p->is_word = true;
    }

    bool search(string word) {
        return dfs(word, root, 0);
    }

    bool dfs(const string & word, TrieNode *p, int index){
        if(index == word.size()){
            return p->is_word;
        }

        if(word[index] == '.'){
            for(auto &it : p->children){
                if(it && dfs(word, it, index + 1)){
                    return true;
                }
            }
            return false;
        }else{
            return p->children[word[index] - 'a'] &&
            dfs(word, p->children[word[index] - 'a'], index + 1);
        }

    }
private:
    TrieNode *root;
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值