数据结构--前缀树(Trie)

1. 简介

前缀树是一种数据结构,常用来字符搜索。

2. 实现

包含的操作主要是:

  • 加入串
  • 搜索串

代码实现,直接用leetcode_208的题解咯。

  • 代码
cpp 复制代码
class Trie {
public:
    Trie():isEnd(false){
        for ( int i = 0; i < 26;++i)
            child[i] = nullptr;
    }
    ~Trie() {
        for ( int i = 0; i < 26; ++i ) {
            if (child[i]) {
                delete child[i];
                child[i] = nullptr;
            }
        }
    }
    
    void insert(string word) {

        Trie *cur = this;
        int sz = word.size();
        for (int i = 0; i < sz; ++i) {
            int idx = word[i] - 'a';
            if ( cur->child[idx] == nullptr) {
                Trie *nxt = new Trie();
                cur->child[idx] = nxt;
            }

            cur = cur->child[idx];
        }
        cur->isEnd = true;
    }
    
    bool search(string word) {

        Trie *cur = this;

        int sz = word.size();
        for (int i = 0; i < sz; ++i) {
            int idx = word[i] - 'a';
            if (cur->child[idx] == nullptr)
                return false;
            cur = cur->child[idx];
        }
        return cur->isEnd;
    }
    
    bool startsWith(string prefix) {

        int sz = prefix.size();

        Trie *cur = this;
        for (int i = 0; i < sz; ++i ) {
            int idx = prefix[i] - 'a';
            if (cur->child[idx] == nullptr)
                return false;
            cur = cur->child[idx];
        }
        return true;
    }
private:
    bool isEnd;
    Trie *child[26];
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
相关推荐
guslegend13 小时前
第4讲:应用架构与代码组织
数据结构·人工智能·架构
Lewiis14 小时前
白话选择排序
数据结构·算法·排序算法
如竟没有火炬14 小时前
乘法表中第K小的数——二分
开发语言·数据结构·python·算法·leetcode·职场和发展·动态规划
吃好睡好便好15 小时前
矩阵的乘法运算
数据结构·人工智能·学习·线性代数·算法·matlab·矩阵
丘山望岳16 小时前
藤萝垂序——二叉搜索树
开发语言·数据结构·c++
我叫张小白。17 小时前
Redis常用数据结构与命令详解
数据结构·数据库·redis
01_ice19 小时前
C语言复杂度
数据结构
05候补工程师19 小时前
【408高分笔记】数据结构冲刺:二叉树遍历性质、特殊形态与栈的跨界联动秒杀技巧
数据结构·经验分享·笔记·考研·算法
菜菜的顾清寒19 小时前
力扣HOT100(36)二分查找-搜索插入位置
数据结构·算法·leetcode
Dlrb121119 小时前
数据结构-树与二叉树
数据结构·二叉树·深度优先··广度优先·层序遍历