数据结构--前缀树(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);
 */
相关推荐
散1127 小时前
01数据结构-图的概念和图的存储结构
数据结构
_poplar_10 小时前
09 【C++ 初阶】C/C++内存管理
c语言·开发语言·数据结构·c++·git·算法·stl
屁股割了还要学14 小时前
【数据结构入门】栈和队列
c语言·开发语言·数据结构·学习·算法·青少年编程
啊阿狸不会拉杆18 小时前
《算法导论》第 13 章 - 红黑树
数据结构·c++·算法·排序算法
三次拒绝王俊凯18 小时前
用生活日常的案例来介绍“程序运行时,对函数的调用一般有两种形式:传值调用和引用调用 和 这两种调用有什么区别?
java·数据结构
码破苍穹ovo1 天前
堆----3.数据流的中位数
java·数据结构·算法·力扣
武文斌771 天前
数据结构:哈希表、排序和查找
数据结构·散列表
Shun_Tianyou1 天前
Python Day25 进程与网络编程
开发语言·网络·数据结构·python·算法
Hx__2 天前
Redis中String数据结构为什么以长度44为embstr和raw实现的分界线?
数据结构·数据库·redis
Skylar_.2 天前
嵌入式 - 数据结构:哈希表和排序与查找算法
数据结构·算法·嵌入式·哈希算法·散列表