前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用 JavaScript 实现单词查找树

用 JavaScript 实现单词查找树

作者头像
疯狂的技术宅
发布2020-02-18 12:31:20
7090
发布2020-02-18 12:31:20
举报
文章被收录于专栏:京程一灯

每日前端夜话第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 类的属性为valueisEndarr。变量 arr 是长度为 26 的数组,其中填充了 null 值。

代码语言:javascript
复制
class TrieNode {
    constructor() {
        this.value = undefined;
        this.isEnd = false;
        this.arr = new Array(26).fill(null);
    }
}

TrieTree 类具有 insertsearchNodestartsWithprintStringgetRoot 方法。可以用 startsWith 方法执行前缀搜索。insert方法将字符串和值作为参数。

代码语言:javascript
复制
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” 类,还演示了各种方法的用法。

代码语言:javascript
复制
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地址和对象等。

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-01-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端先锋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 动机
  • 方法
  • 实现
  • 应用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档