数据结构--前缀树(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);
 */
相关推荐
故事和你914 小时前
sdut-程序设计基础Ⅰ-实验五一维数组(8-13)
开发语言·数据结构·c++·算法·蓝桥杯·图论·类和对象
郝YH是人间理想9 小时前
Pandas库DataFrame数据结构
数据结构·pandas
j_xxx404_10 小时前
C++算法:前缀和与哈希表实战
数据结构·算法·leetcode
我能坚持多久10 小时前
【初阶数据结构07】——栈与队列的代码实现与解析
数据结构
We་ct10 小时前
LeetCode 22. 括号生成:DFS回溯解法详解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
Aaswk12 小时前
蓝桥杯2025年第十六届省赛真题(更新中)
c语言·数据结构·c++·算法·职场和发展·蓝桥杯
Yvonne爱编码12 小时前
JAVA数据结构 DAY7-二叉树
java·开发语言·数据结构
总斯霖12 小时前
P15445永远在一起!题解(月赛T2)
数据结构·c++·算法·深度优先
像污秽一样13 小时前
算法设计与分析-习题4.5
数据结构·算法·排序算法·剪枝
样例过了就是过了13 小时前
LeetCode热题100 全排列
数据结构·c++·算法·leetcode·dfs