题目
创建 Trie 类,支持 insert(word)、search(word) 和 startsWith(prefix) 操作。输入契约:无初始输入,Trie 初始为空,通过 insert 添加单词;输出契约:一个带上述三个方法的 Trie 实例。公开样例:插入 "apple" 后 search("apple") 为 true,startsWith("app") 也为 true。隐藏测试要求未插入时 search("app") 返回 false,以及插入 "app" 后 search("app") 返回 true。
解题思路
每个节点保存 children 映射和 isEnd 布尔标记。插入沿字符逐层创建或复用节点,末尾置 isEnd;查找同样逐层下降,search 还要求终点 isEnd 为 true;startsWith 只要求路径存在。三个操作时间均为 O(m),m 为单词或前缀长度,空间与节点数成正比。
参考实现要点
定义 TrieNode 构造函数,children 用普通对象、isEnd 初始为 false;Trie 构造时建立 root。insert 用 for…of 遍历字符,缺失子节点时新建,最后标记 isEnd。search 和 startsWith 共用下降逻辑,区别只在返回值:前者返回 node.isEnd,后者走到路径末尾即返回 true。
常见错误
原文强调把 search 与 startsWith 混淆:search 必须检查 isEnd,startsWith 只需路径存在。另一个边界坑来自隐藏测试:先 search("app") 再插入时,若在 insert 前缓存了结果,或误把根节点当成单词结尾,会得到错误的 true;应保证 isEnd 只在完整单词末尾设置。
验证方式
用 Node.js 创建实例,先断言 search("app") 为 false,再 insert("apple") 后断言 search("apple") 与 startsWith("app") 为 true,并插入 "app" 验证 search("app") 为 true;再测空前缀与重复插入同一单词等边界。
代码示例
class TrieNode {
constructor() { this.children = {}; this.isEnd = false; }
}
class Trie {
constructor() { this.root = new TrieNode(); }
insert(word) {
let node = this.root;
for (const ch of word) {
if (!node.children[ch]) node.children[ch] = new TrieNode();
node = node.children[ch];
}
node.isEnd = true;
}
search(word) {
let node = this.root;
for (const ch of word) {
if (!node.children[ch]) return false;
node = node.children[ch];
}
return node.isEnd;
}
startsWith(prefix) {
let node = this.root;
for (const ch of prefix) {
if (!node.children[ch]) return false;
node = node.children[ch];
}
return true;
}
}