数据结构--前缀树(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);
 */
相关推荐
夏末秋也凉3 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
王老师青少年编程3 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
liuyuzhongcc6 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
计算机小白一个7 小时前
蓝桥杯 Java B 组之背包问题、最长递增子序列(LIS)
java·数据结构·蓝桥杯
卑微的小鬼8 小时前
数据库使用B+树的原因
数据结构·b树
cookies_s_s8 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法
醉城夜风~10 小时前
[数据结构]双链表详解
数据结构
gyeolhada10 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~10 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
刃神太酷啦12 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组