【C++前缀树】Trie简介、构造及应用

一、简介

Trie,又称前缀树或字典树,是一棵有根树,一般应用于字符串(本文假设字符串全为小写英文字母构成)的操作,其每个节点包含以下字段:

  • 指向子节点的指针数组 children ,对于全为小写英文字母的字符串而言, children 数组长度为 26,即小写英文字母的数量。
  • 布尔字段 isEnd ,表示该节点是否为字符串的结尾。

二、构造

class Trie {
private:
    vector<Trie *> children;
    bool isEnd;
    Trie *searchPrefix(string pre)
    {
        Trie *node=this;
        for(char c:pre)
        {
            c-='a';
            if(!node->children[c]) return NULL;
            node=node->children[c];
        }
        return node;
    }
    
public:
    /** Initialize your data structure here. */
    Trie():children(26),isEnd(false) {

    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        Trie *node=this;
        for(char c:word)
        {
            c-='a';
            if(!node->children[c]) node->children[c]= new Trie();
            node=node->children[c];
        }
        node->isEnd=true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie *node=searchPrefix(word);
        return node && node->isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Trie *node=searchPrefix(prefix);
        return node;
    }
};

三、应用

1、神奇的字典(简单应用)

力扣https://leetcode-cn.com/problems/US1pGT/

2、最短的单词编码(后缀树)

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/iSwD2y/

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

棱角码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值