浅谈字典树(前缀树)

1.什么事字典树

就是把英文单词中每个字符挂在树上。如果某些单词有共同的字串,就复用树上的边或者节点。

2.字典树的三个基本性质

Tire的核心思想是时间换空间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
(1)根节点不包含字符,除根节点外每一个节点都只包含一个字符。
(2)从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
(3)每个节点的所有子节点包含的字符都不相同。

3.C++代码

#include <iostream>
#include <vector>
#include <string>

class Trie {
public:
    std::vector<Trie*> children;
    bool isEnd;
public:
    Trie() : children(26, nullptr), isEnd(false) {}
    /* 边上是字符 */
    void insert(std::string word) {
        Trie* node = this;
        for (auto ch : word) {
            if (node->children[ch - 'a'] == nullptr) {
                node->children[ch - 'a'] = new Trie();
            }
            node = node->children[ch - 'a'];
        }
        node->isEnd = true;
    }
    
    bool search(std::string word) {
        Trie* node = this;
        for (auto ch : word) {
            if (node->children[ch - 'a'] != nullptr) {
                node = node->children[ch - 'a'];
            } else {
                return false;
            }
        }
        if (node->isEnd == true) {
            return true;
        } else {
            return false;
        }
    }
    
    bool startsWith(std::string prefix) {
        Trie* node = this;
        for (auto ch : prefix) {
            if (node->children[ch - 'a'] != nullptr) {
                node = node->children[ch - 'a'];
            } else {
                return false;
            }
        }
        return true;
    }
};

int main()
{
    Trie* obj = new Trie();
    obj->insert("beijing");
    obj->insert("shanghai");
    bool res1 = obj->search("beijing");
    std::cout << "beijing is found: " << res1 << std::endl;
    bool res2 = obj->startsWith("shang");
    std::cout << "shang is found in prefix: " << res2 << std::endl;
}

上述代码定义了一个类Trie,它的成员数据有两个:一个是Children,记录了孩子节点有哪些;第二个是isEnd,表示字符串的结束,还有this指针的妙用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值