Trie

简介

根据维基百科介绍:

在计算机科学中,trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。

图示

在这里插入图片描述

实现

class TrieNode {
	constructor() {
		this.path = 0;	// 记录每个字符经过该节点的次数;
		this.end = 0;	// 记录经过该节点的字符串个数;
		this.next = new Array(26).fill(null);	// 记录节点的子路径,26个英文字母有26条路径;初始为null;
	}
}

class Trie {
	constructor() {
		this.root = new TrieNode();
	}
	insert(str) {
		if (!str) return;
		let node = this.root;
		for(let i = 0, len = str.length; i < len; i++) {
			let index = str[i].charCodeAt() - 'a'.charCodeAt();
			if (!node.next[index]) {
				node.next[index] = new TrieNode;
			}
			node.path += 1;
			node = node.next[index];
		}
		node.end += 1;
	}
	search(str) {
		if (!str) return;
		let node = this.root;
		for(let i = 0, len = str.length; i < len; i++) {
			let index = str[i].charCodeAt() - 'a'.charCodeAt();
			if (!node.next[index]) {
				return 0;
			}
			node = node.next[index];
		}
		return node.end;
	}
	delete(str) {
		if (!this.search(str)) return;
		let node = this.root;
		for(let i = 0, len = str.length; i < len; i++) {
			let index = str[i].charCodeAt() - 'a'.charCodeAt();
			if (--node.next[index].path === 0 ) {
				node.next[index] = null;
			}
			node = node.next[index];
		}
		node.end -= 1;
	}
}

参考文献

  1. https://zh.wikipedia.org/wiki/Trie
  2. https://yuchengkai.cn/docs/cs/dataStruct.html#%E6%A6%82%E5%BF%B5-5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Neil-

你们的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值