每日前端夜话第270篇
翻译:疯狂的技术宅
作者:Hussain Mir Ali
来源:softnami
正文共:870 字
预计阅读时间:6分钟
对于搜索字符串的需求,在最坏的情况下,二叉搜索树的时间复杂度可能为 O(n),“n” 是二叉树中存储的字符串的总数量。所以为了在最佳时间内搜索字符串,需要一种性能更好的数据结构。Trie 树(又名单词搜索树)可以避免在搜索字符串时遍历整个树。仅包含字母的字符串会把 trie 节点的子级数量限制为 26。这样搜索字符串的时间复杂度为 O(s),其中 “s” 为字符串的长度。与二进制搜索树相比,trie 树在搜索字符串方面效率更高。
trie 树中单个节点的结构由长度为 26 的数组和一个布尔值组成,这个布尔值用来标识其是否为叶子节点。此外,叶子节点可以具有整数值或映射到字符串的其他类型的值。数组中的每个索引代表从 a 到 z 的字母,并且每个索引可以有一个 TrieNode
实例。
trie node
上图表示 trie 树中的根节点。
该实现包含两个类,一个用于 trie 节点,另一个用于 trie 树。实现的语言是带有 ES6 规范的 JavaScript。
TrieNode
类的属性为value
,isEnd
和 arr
。变量 arr
是长度为 26 的数组,其中填充了 null
值。
class TrieNode {
constructor() {
this.value = undefined;
this.isEnd = false;
this.arr = new Array(26).fill(null);
}
}
TrieTree
类具有 insert
、searchNode
、startsWith
、printString
和 getRoot
方法。可以用 startsWith
方法执行前缀搜索。insert
方法将字符串和值作为参数。
class TrieTree {
constructor() {
this.root = new TrieNode();
}
insert(word, value) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
const index = parseInt(word[i], 36) - 10;
if (node.arr[index] === null) {
const temp = new TrieNode();
node.arr[index] = temp;
node = temp;
} else {
node = node.arr[index];
}
}
node.isEnd = true;
node.value = value;
}
getRoot() {
return this.root;
}
startsWith(prefix) {
const node = this.searchNode(prefix);
if (node == null) {
return false;
} else {
this.printStrings(node, "");
return true;
}
}
printStrings(node, prefix) {
if (node.isEnd) console.log(prefix);
for (let i = 0; i < node.arr.length; i++) {
if (node.arr[i] !== null) {
const character = String.fromCharCode('a'.charCodeAt() + i);
this.printStrings(node.arr[i], prefix + "" + (character));
}
}
}
searchNode(str) {
let node = this.root;
for (let i = 0; i < str.length; i++) {
const index = parseInt(str[i], 36) - 10;
if (node.arr[index] !== null) {
node = node.arr[index];
} else {
return null;
}
}
if (node === this.root)
return null;
return node;
}
}
下面的代码显示了如何实例化 “TrieTree” 类,还演示了各种方法的用法。
const trieTree = new TrieTree();
trieTree.insert("asdfasdf", 5);
trieTree.insert("cdfasdfas", 23);
trieTree.insert("cdfzsvljsdf", 42);
let answer = trieTree.searchNode("asdfasdf");
console.log(answer.value); //5
answer = trieTree.startsWith("cdf");
console.log(answer);
//asdfas
//zsvljsdf
//true
不同方法的时间和空间复杂度如下:
在前端开发中,trie 树可用于以下程序:
此外 trie 树可以用来存储电话号码、IP地址和对象等。
原文:https://www.softnami.com/posts_pr/trie-tree-with-javascript.html