数据结构--前缀树(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);
 */
相关推荐
LYFlied16 分钟前
【算法解题模板】-【回溯】----“试错式”问题解决利器
前端·数据结构·算法·leetcode·面试·职场和发展
lxh011325 分钟前
最长有效括号
数据结构·算法
fei_sun30 分钟前
【总结】【数据结构】【OS】【计组】【计网】
数据结构
Code Slacker35 分钟前
LeetCode Hot100 —— 普通数组(面试纯背版)(五)
数据结构·c++·算法·leetcode·面试
sin_hielo37 分钟前
leetcode 3573(买卖股票问题,状态机dp)
数据结构·算法·leetcode
廋到被风吹走37 分钟前
【数据库】【Redis】数据结构全景图:命令、场景与避坑指南
数据结构·数据库·redis
松涛和鸣41 分钟前
34、 Linux IPC进程间通信:无名管道(Pipe) 和有名管道(FIFO)
linux·服务器·c语言·网络·数据结构·数据库
xiaoxue..2 小时前
二叉树深度解析:从基础结构到实战应用
javascript·数据结构·面试
风筝在晴天搁浅2 小时前
hot100 3.无重复字符的最长子串
数据结构·算法·leetcode
蒙奇D索大3 小时前
【数据结构】考研408 | 开放定址法精讲:连续探测的艺术与代价
数据结构·笔记·考研·改行学it