跳到主要内容

认识

Trie(发音类似 "try")或者说前缀树, 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查、处理字符串匹配问题的数据结构、解决集合中查找固定前缀字符串等场景。

实现


字典树结构

Trie 又称前缀树字典树,是一棵有根树,其每个节点包含以下字段:

  • children: 数组长度为 26,即小写英文字母的数量.此时 children[0] 对应小写字母 achildren[1] 对应小写字母 b,…,children[25] 对应小写字母 z

  • 布尔字段: isEnd,表示该节点是否为字符串的结尾

插入字符串

我们从字典树的根开始,插入字符串。对于当前字符对应的子节点,有两种情况:

  • 子节点存在。沿着指针移动到子节点,继续处理下一个字符

  • 子节点不存在。创建一个新的子节点,记录在 children 数组的对应位置上,然后沿着指针移动到子节点,继续搜索下一个字符

重复以上步骤,直到处理字符串的最后一个字符,然后将当前节点标记为字符串的结尾。

insert(word) {
let node = this;
for (let i = 0; i < word.length; i++) {
const char = word[i];
const index = char.charCodeAt() - "a".charCodeAt();
if (node.children[index] === 0) {
node.children[index] = new Trie();
}
node = node.children[index];
}
node.isEnd = true;
}

搜索前缀

我们从字典树的根开始,查找前缀。对于当前字符对应的子节点,有两种情况:

  • 子节点存在。沿着指针移动到子节点,继续搜索下一个字符。
  • 子节点不存在。说明字典树中不包含该前缀,返回空指针。

重复以上步骤,直到返回空指针或搜索完前缀的最后一个字符。

若搜索到了前缀的末尾,就说明字典树中存在该前缀。此外,若前缀末尾对应节点的 isEnd 为真,则说明字典树中存在该字符串。

searchPrefix(prefix) {
let node = this;
for (let i = 0; i < prefix.length; i++) {
const char = prefix[i];
const index = char.charCodeAt() - "a".charCodeAt();
if (node.children[index] === 0) {
return null;
}
node = node.children[index];
}
return node;
}

完整代码


class Trie {
constructor() {
this.children = new Array(26).fill(0);
this.isEnd = false;
}
insert(word) {
let node = this;
for (let i = 0; i < word.length; i++) {
const char = word[i];
const index = char.charCodeAt() - "a".charCodeAt();
if (node.children[index] === 0) {
node.children[index] = new Trie();
}
node = node.children[index];
}
node.isEnd = true;
}
searchPrefix(prefix) {
let node = this;
for (let i = 0; i < prefix.length; i++) {
const char = prefix[i];
const index = char.charCodeAt() - "a".charCodeAt();
if (node.children[index] === 0) {
return null;
}
node = node.children[index];
}
return node;
}
search(word) {
const node = this.searchPrefix(word);
return node != null && node.isEnd;
}
startsWith(prefix) {
return this.searchPrefix(prefix) != null;
}
}