数据结构--前缀树(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);
 */
相关推荐
hweiyu0016 分钟前
数据结构:后缀自动机
数据结构
小尧嵌入式16 分钟前
C语言中的面向对象思想
c语言·开发语言·数据结构·c++·单片机·qt
花月C21 分钟前
基于Redis的BitMap数据结构实现签到业务
数据结构·数据库·redis
一杯美式 no sugar23 分钟前
数据结构——单向无头不循环链表
c语言·数据结构·链表
ss27325 分钟前
阻塞队列:三组核心方法全对比
java·数据结构·算法
埃伊蟹黄面1 小时前
算法 --- hash
数据结构·c++·算法·leetcode
fei_sun1 小时前
【数据结构】2025年真题
数据结构
我在人间贩卖青春1 小时前
线性表之队列
数据结构·队列
1024小神1 小时前
swift中 列表、字典、集合、元祖 常用的方法
数据结构·算法·swift
Java水解2 小时前
基于Rust实现爬取 GitHub Trending 热门仓库
数据结构·后端