高级数据结构 -- Trie前缀树(字典树)

本文介绍了Trie树(字典树),一种用于字符串处理的数据结构,常用于搜索引擎系统以减少查询时间。文章讨论了Trie树的主要操作:插入、删除、查询和前缀查询,并提供了具体的实现示例。此外,还通过LeetCode的677题解释了如何使用Trie树实现键值映射的功能。
摘要由CSDN通过智能技术生成

字典树又称为前缀树或Trie树,是处理字符串常见的数据结构。Trie经常被搜索引擎系统。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较。

假设组成所有单词的字符仅是“a”~"z",请实现字典树结构,并包含以下四个主要功能:

void insert(String word):添加word,可重复添加。
void delete(String word):删除word,如果word添加过多次,仅删除一次。
int search(String word):查询word是否在字典树中,返回word的个数。
int serachPrefix(String pre):返回以字符串pre为前缀的单词数量。
 

实现代码如下:

package 树;
class TrieNode {
	public int pass;
	public int end;
	public TrieNode[] nexts;
	public TrieNode() {
		//pass表示经过包含这个字符的字符串的个次数
		pass = 0;
		//end表示以这个字符结尾的字符串的个数
		end = 0;
		//表示26个字母
		nexts = new TrieNode[26];
	}
}

public class Trie {
	private TrieNode root;

	public Trie() {
		root = new TrieNode();
	}
	
	public void insert(String word) {
		if (word == null) {
			return;
		} 
		char[] chs = word.toCharArray();
		TrieNode node = root;
		node.pass++; //经过的次数+1
		int index = 0;		
		for (int i = 0; i < chs.length; i++) {  //从左往右遍历字符
			index = chs[i] - 'a';               
			//如果没有这条路劲,则新建路径
			if (node.nexts[index] == null) {
				node.nexts[index] = new TrieNode();
			}
			//有则前往子路径
			node = node.nexts[index];
			node.pass++;
		}
		node.end++;//字符串结束,以该字符结尾的字符串数量+1
	}
	
	public int search(String word) {
		if (word == null) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Free的午后

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

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

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

打赏作者

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

抵扣说明:

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

余额充值