用 JavaScript 实现单词查找树

用 JavaScript 实现单词查找树

动机


对于搜索字符串的需求,在最坏的状况下,二叉搜索树的时间复杂度可能为 O(n),“n” 是二叉树中存储的字符串的总数量。因此为了在最佳时间内搜索字符串,须要一种性能更好的数据结构。Trie 树(又名单词搜索树)能够避免在搜索字符串时遍历整个树。仅包含字母的字符串会把 trie 节点的子级数量限制为 26。这样搜索字符串的时间复杂度为 O(s),其中 “s” 为字符串的长度。与二进制搜索树相比,trie 树在搜索字符串方面效率更高。javascript

方法


trie 树中单个节点的结构由长度为 26 的数组和一个布尔值组成,这个布尔值用来标识其是否为叶子节点。此外,叶子节点能够具备整数值或映射到字符串的其余类型的值。数组中的每一个索引表明从 a 到 z 的字母,而且每一个索引能够有一个 TrieNode 实例。
用 JavaScript 实现单词查找树html

trie node
上图表示 trie 树中的根节点。前端

实现


该实现包含两个类,一个用于 trie 节点,另外一个用于 trie 树。实现的语言是带有 ES6 规范的 JavaScript。java

TrieNode 类的属性为value,isEnd和 arr。变量 arr 是长度为 26 的数组,其中填充了 null 值。node

1class TrieNode {
2    constructor() {
3        this.value = undefined;
4        this.isEnd = false;
5        this.arr = new Array(26).fill(null);
6    }
7}

TrieTree 类具备 insert、searchNode、startsWith、printString 和 getRoot 方法。能够用 startsWith 方法执行前缀搜索。insert方法将字符串和值做为参数。数组

1class TrieTree {
 2
 3    constructor() {
 4        this.root = new TrieNode();
 5    }
 6
 7    insert(word, value) {
 8        let node = this.root;
 9        for (let i = 0; i < word.length; i++) {
10            const index = parseInt(word[i], 36) - 10;
11
12            if (node.arr[index] === null) {
13                const temp = new TrieNode();
14                node.arr[index] = temp;
15                node = temp;
16            } else {
17                node = node.arr[index];
18            }
19        }
20        node.isEnd = true;
21        node.value = value;
22    }
23
24    getRoot() {
25        return this.root;
26    }
27
28    startsWith(prefix) {
29        const node = this.searchNode(prefix);
30        if (node == null) {
31            return false;
32        } else {
33            this.printStrings(node, "");
34            return true;
35        }
36    }
37
38    printStrings(node, prefix) {
39        if (node.isEnd) console.log(prefix);
40        for (let i = 0; i < node.arr.length; i++) {
41            if (node.arr[i] !== null) {
42                const character = String.fromCharCode('a'.charCodeAt() + i);
43                this.printStrings(node.arr[i], prefix + "" + (character));
44            }
45        }
46    }
47
48    searchNode(str) {
49        let node = this.root;
50        for (let i = 0; i < str.length; i++) {
51            const index = parseInt(str[i], 36) - 10;
52            if (node.arr[index] !== null) {
53                node = node.arr[index];
54            } else {
55                return null;
56            }
57        }
58
59        if (node === this.root)
60            return null;
61
62        return node;
63    }
64}

下面的代码显示了如何实例化 “TrieTree” 类,还演示了各类方法的用法。数据结构

1const trieTree = new TrieTree();
 2trieTree.insert("asdfasdf", 5);
 3trieTree.insert("cdfasdfas", 23);
 4trieTree.insert("cdfzsvljsdf", 42);
 5
 6let answer = trieTree.searchNode("asdfasdf");
 7console.log(answer.value); //5
 8answer = trieTree.startsWith("cdf");
 9console.log(answer);
10//asdfas
11//zsvljsdf
12//true

不一样方法的时间和空间复杂度以下:ide

  • searchNode:时间复杂度:O(s),'s' 是字符串的长度,空间复杂度:O(1),由于没有使用额外的数据结构,例如队列或栈。post

  • insert:时间复杂度:O(s),“s”是字符串长度,空间复杂度:O(ns),其中 “n” 是 trie 树中 key 的数量,“s” 是字符串的长度。性能

  • startsWith:时间复杂度:O(s),'s' 是字符串的长度,'k' 是剩余匹配字符串的最大长度,空间复杂度:O(k),其中 'k' 是其他匹配字符串的最大长度。

应用


在前端开发中,trie 树可用于如下程序:

  • 自动完成和提早输入功能。

  • 拼写检查。

  • 搜索。

  • 排序。

此外 trie 树能够用来存储电话号码、IP地址和对象等。

原文:https://www.softnami.com/posts_pr/trie-tree-with-javascript.html

相关文章
相关标签/搜索