用 JavaScript 实现单词查找树

1,507 阅读3分钟

作者:Hussain Mir Ali

翻译:疯狂的技术宅

原文:www.softnami.com/posts_pr/tr…

未经允许严禁转载

动机

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

方法

trie 树中单个节点的结构由长度为 26 的数组和一个布尔值组成,这个布尔值用来标识其是否为叶子节点。此外,叶子节点可以具有整数值或映射到字符串的其他类型的值。数组中的每个索引代表从 a 到 z 的字母,并且每个索引可以有一个 TrieNode 实例。

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

实现

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

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

class TrieNode {
    constructor() {
        this.value = undefined;
        this.isEnd = false;
        this.arr = new Array(26).fill(null);
    }
}

TrieTree 类具有 insertsearchNodestartsWithprintStringgetRoot 方法。可以用 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

不同方法的时间和空间复杂度如下:

  • searchNode:时间复杂度:O(s),'s' 是字符串的长度,空间复杂度:O(1),因为没有使用额外的数据结构,例如队列或栈。
  • insert:时间复杂度:O(s),“s”是字符串长度,空间复杂度:O(ns),其中 “n” 是 trie 树中 key 的数量,“s” 是字符串的长度。
  • startsWith:时间复杂度:O(s),'s' 是字符串的长度,'k' 是剩余匹配字符串的最大长度,空间复杂度:O(k),其中 'k' 是其余匹配字符串的最大长度。

应用

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

  • 自动完成和提前输入功能。
  • 拼写检查。
  • 搜索。
  • 排序。

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

欢迎关注前端公众号:前端先锋,免费领取 Vue、React 性能优化教程。