【数据结构-前缀树】力扣208. 实现 Trie (前缀树)

Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补全和拼写检查。

请你实现 Trie 类:

Trie() 初始化前缀树对象。

void insert(String word) 向前缀树中插入字符串 word 。

boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。

boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

示例:

输入

"Trie", "insert", "search", "search", "startsWith", "insert", "search"

\[\], \["apple"\], \["apple"\], \["app"\], \["app"\], \["app"\], \["app"\]

输出

null, null, true, false, true, null, true

解释

Trie trie = new Trie();

trie.insert("apple");

trie.search("apple"); // 返回 True

trie.search("app"); // 返回 False

trie.startsWith("app"); // 返回 True

trie.insert("app");

trie.search("app"); // 返回 True

字典树

csharp 复制代码
class Trie {
private:
    vector<Trie*> children;
    bool isEnd;

    Trie* searchPrefix(string prefix){
        Trie* node = this;
        for(char ch : prefix){
            ch -= 'a';
            if(node->children[ch] == nullptr){
                return nullptr;
            }
            node = node->children[ch];
        }
        return node;
    }
public:
    Trie(): children(26, nullptr), isEnd(false) {
    }
    
    void insert(string word) {
        Trie* node = this;
        for(char ch : word){
            ch -= 'a';
            if(node->children[ch] == nullptr){
                node->children[ch] = new Trie();
            }
            node = node->children[ch];
        }
        node->isEnd = true;
    }
    
    bool search(string word) {
        Trie* node = this->searchPrefix(word);
        return node != nullptr && node->isEnd;
    }
    
    bool startsWith(string prefix) {
        return this->searchPrefix(prefix) != nullptr;
    }
};

时间复杂度:初始化为 O(1) ,其余操作为 O(∣S∣),其中 ∣S∣ 是每次插入或查询的字符串的长度。
空间复杂度:O(∣T∣⋅Σ),其中 ∣T∣ 为所有插入字符串的长度之和,Σ 为字符集的大小,本题 Σ=26。

我们要构造前缀树,首先我们构造一个vector容器children,每个元素是一个Trie,并且我们初始化children(26, nullptr),说明一个节点node最多可以有26个子节点,也就是26个不同字符。

字典数的核心是searchPrefix函数,也就是查找这个字典树的前缀是否包含word单词。首先我们将字符串prefix拆解成一个个字符,先通过-'a'将它换算成ascii码,然后从字典树的根节点进行查找,根节点不储存信息,所以我们检查node->children[ch]是否存在,如果该节点存在的话我们就将node移到该节点,然后我们继续遍历prefix的下一个字符,如果prefix所有字符都能依次在字典树沿着某条路径找到,那么他就会返回prefix的最后一个节点的指针。

这么做的目的就是比如我们在调用startsWith函数的时候,我们只要检查返回的node是不是一个空指针就能判断之前已经插入的字符串 word 的前缀之一有没有 prefix。

接下来我们查看insert函数,我们一样把要插入的单词拆成一个个字符,如果我们沿着字典树某个路径找不到某个字符,那么就会new一个node->children[ch],并且将node移到新开辟的节点,在插入完最后一个字符的时候,会进行一个标记node->isEnd = true;,代表该节点是一个单词的结尾,这样做的目的是调用search函数的时候,可以检查字典树中表示的字符串是否是一个单词。

相关推荐
夏鹏今天学习了吗7 小时前
【LeetCode热题100(87/100)】最小路径和
算法·leetcode·职场和发展
Lips6119 小时前
2026.1.20力扣刷题笔记
笔记·算法·leetcode
鱼跃鹰飞10 小时前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
好评12410 小时前
【C++】二叉搜索树(BST):从原理到实现
数据结构·c++·二叉树·二叉搜索树
程序猿炎义11 小时前
【Easy-VectorDB】Faiss数据结构与索引类型
数据结构·算法·faiss
jiaguangqingpanda13 小时前
Day24-20260120
java·开发语言·数据结构
52Hz11813 小时前
力扣24.两两交换链表中的节点、25.K个一组反转链表
算法·leetcode·链表
老鼠只爱大米13 小时前
LeetCode经典算法面试题 #160:相交链表(双指针法、长度差法等多种方法详细解析)
算法·leetcode·链表·双指针·相交链表·长度差法
ValhallaCoder13 小时前
Day53-图论
数据结构·python·算法·图论
老鼠只爱大米13 小时前
LeetCode经典算法面试题 #84:柱状图中最大的矩形(单调栈、分治法等四种方法详细解析)
算法·leetcode·动态规划·单调栈·分治法·柱状图最大矩形