力扣 211. 添加与搜索单词 - 数据结构设计 字典树

26 篇文章 0 订阅
13 篇文章 0 订阅
本文介绍了一种使用字典树(Trie树)解决LeetCode中添加和搜索单词数据结构问题的方法。通过建立TireNode结构,实现了字符串的插入和搜索功能,特别地,对于包含字符'.'的情况,采用深度优先搜索处理。字典树是一种高效的数据结构,支持快速前缀匹配和插入操作。
摘要由CSDN通过智能技术生成

https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/
在这里插入图片描述
思路:字典树经典题目。看数据范围,暴力比对的话大概率会超时。字典树就是前缀树,支持插入字符串、快速检索字符串 or 前缀是否出现过,当然它还有一些变体存在,比如01字典树等。详见我的这篇博客,此处就不多说了。字符 “.” 其实也挺好处理的,写个深搜嘛。

class TireNode{
public:
    array<TireNode*, 26> children;
    bool isEnd=false;
};

class TireTree{
public:

    TireTree():root(new TireNode()){}

    void insert(const string& word)
    {
        TireNode *cur=root;
        for(char ch: word)
        {
            int idx=ch-'a';
            if(!cur->children[idx])
                cur->children[idx]=new TireNode();
            cur=cur->children[idx];
        }
        cur->isEnd=true;
    }

    bool search(const string& word)
    {
        return _search(word, root);
    }

private:
    TireNode *root;

    bool _search(const string& word,TireNode *cur, int pos=0)
    {
        int siz=word.size();
        if(pos==siz)
            return cur->isEnd;
        int idx=word[pos]-'a';
        if(word[pos]=='.')
        {
            for(int j=0;j<26;j++)
                if(cur->children[j]&&_search(word, cur->children[j], pos+1))
                    return true;
            return false;
        }
        else if(!cur||!cur->children[idx])
            return false;
        else
            return _search(word, cur->children[idx], pos+1);
    }
};

class WordDictionary {
public:
    WordDictionary() {

    }
    
    void addWord(string word) {
        tireTree.insert(word);
    }
    
    bool search(string word) {
        return tireTree.search(word);
    }
private:
    TireTree tireTree;
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值