数据结构--前缀树(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);
 */
相关推荐
重生之我要进大厂4 小时前
LeetCode 876
java·开发语言·数据结构·算法·leetcode
Happy鱿鱼4 小时前
C语言-数据结构 有向图拓扑排序TopologicalSort(邻接表存储)
c语言·开发语言·数据结构
KBDYD10104 小时前
C语言--结构体变量和数组的定义、初始化、赋值
c语言·开发语言·数据结构·算法
Crossoads5 小时前
【数据结构】排序算法---桶排序
c语言·开发语言·数据结构·算法·排序算法
QXH2000005 小时前
数据结构—单链表
c语言·开发语言·数据结构
imaima6665 小时前
数据结构----栈和队列
开发语言·数据结构
David猪大卫6 小时前
数据结构修炼——顺序表和链表的区别与联系
c语言·数据结构·学习·算法·leetcode·链表·蓝桥杯
Iceberg_wWzZ6 小时前
数据结构(Day14)
linux·c语言·数据结构·算法
Beauty.5686 小时前
P1328 [NOIP2014 提高组] 生活大爆炸版石头剪刀布
数据结构·c++·算法
爱棋笑谦6 小时前
二叉树计算
java·开发语言·数据结构·算法·华为od·面试