前缀树Tria

前缀树

0、题目

力扣:
208、实现Trie树
212、单词搜索2

1、概念

参考:https://blog.csdn.net/u011764940/article/details/121970140

概念:Trie树,即字典树,又称单词查找树或键树,是一种多叉树结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较。

图片理解可参考博客。

2、实现

class Trie {
private:
    string word;
    unordered_map<char, Trie *> children;
public:
    Trie() {
        word = "";
    }
    
    void insert(string word) {
        Trie *node = this;
        for (auto it : word) {
            if (node->children.count(it) == 0) {
                node->children[it] = new Trie();
            }
            node = node->children[it];
        }
        node->word = word;
    }
    
    bool search(string word) {
        Trie *node = this;
        for (char ch : word) {
            if (node->children.count(ch) == 0) {
                return false;
            }
            node = node->children[ch];
        }
        return node->word.size() != 0;
    }
    
    bool startsWith(string prefix) {
        Trie *node = this;
        for (auto ch : prefix) {
            if (node->children.count(ch) == 0) {
                return false;
            }
            node = node->children[ch];
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值