创见博客
实现 Trie (前缀树)
七崽爱吃小饼干2026/01/13阅读 0专栏 算法合集

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

请你实现 Trie 类:

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

  • void insert(String word) 向前缀树中插入字符串 word 。
  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

示例:

codeType
输入
["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

提示:

  • 1 <= word.length, prefix.length <= 2000
  • word 和 prefix 仅由小写英文字母组成
  • insert、search 和 startsWith 调用次数 总计 不超过 3 * 104 次

解法

ts
class Trie {
    // 核心:每个节点包含 26个字母的子节点数组 + isEnd结束标记
    private children: Trie[];
    private isEnd: boolean;

    constructor() {
        this.children = new Array(26).fill(null); // 初始化26个空位置,对应a-z
        this.isEnd = false; // 默认不是单词结尾
    }

    insert(word: string): void {
        let node: Trie = this;
        for (const c of word) {
            const idx = c.charCodeAt(0) - 'a'.charCodeAt(0); // 转0-25的下标
            if (!node.children[idx]) {
                node.children[idx] = new Trie(); // 不存在则新建子节点
            }
            node = node.children[idx]; // 指针下移
        }
        node.isEnd = true; // 单词遍历完毕,标记结束
    }

    search(word: string): boolean {
        let node: Trie = this;
        for (const c of word) {
            const idx = c.charCodeAt(0) - 'a'.charCodeAt(0);
            if (!node.children[idx]) return false;
            node = node.children[idx];
        }
        return node.isEnd; // 必须是单词结尾才算匹配成功
    }

    startsWith(prefix: string): boolean {
        let node: Trie = this;
        for (const c of prefix) {
            const idx = c.charCodeAt(0) - 'a'.charCodeAt(0);
            if (!node.children[idx]) return false;
            node = node.children[idx];
        }
        return true; // 前缀匹配成功即可
    }
}
评论
0/100