Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
Trie 的应用场景: 一次建树,多次查询
前缀树的3个基本性质:
- 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
- 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
- 每个节点的所有子节点包含的字符都不相同。
前缀树查询和哈希查询的比较(示相对情况而定):
通常字典树的查询时间复杂度是O(logL),L是字符串的长度。
适用场景:
- 字符串的快速检索
- 字符串排序
- 最长公共前缀
- 自动匹配前缀显示后缀
208. 实现 Trie (前缀树)
三个单词 “sea”,”sells”,”she” 的 Trie


class TrieNode {children;isEnd;constructor() {this.children = new Array(26);this.isEnd = false;}}class Trie {root;constructor() {this.root = new TrieNode();}insert(word: string): void {let head = this.root;for (let char of word) {let index = char.charCodeAt(0) - 97;if (!head.children[index]) {head.children[index] = new TrieNode();}head = head.children[index];}head.isEnd = true;}search(word: string): boolean {let head = this.searchPrefix(word);return head != null && head.isEnd;}startsWith(prefix: string): boolean {return this.searchPrefix(prefix) != null;}private searchPrefix(prefix: string) {let head = this.root;for (let char of prefix) {let index = char.charCodeAt(0) - 97;if (!head.children[index]) return null;head = head.children[index];}return head;}}
720. 词典中最长的单词
692. 前K个高频单词
练习:
面试题 17.17. 多次搜索
677. 键值映射
返回所有以该前缀 prefix 开头的键 key 的值的总和
676. 实现一个魔法字典
判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配
