Trie树(字典树)的介绍及Java实现
作者:小楼一夜听春雨 发布时间:2022-06-14 15:38:24
标签:java,trie树,字典树
简介
Trie树,又称为前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。
它的主要特点如下:
根节点不包含字符,除根节点外的每一个节点都只包含一个字符。
从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
每个节点的所有子节点包含的字符都不相同。
如下是一棵典型的Trie树:
Trie的来源是Retrieval,它常用于前缀匹配和词频统计。可能有人要说了,词频统计简单啊,一个hash或者一个堆就可以搞定,但问题来了,如果内存有限呢?还能这么 玩吗?所以这里我们就可以用trie树来压缩下空间,因为公共前缀都是用一个节点保存的。
1、定义
这里为了简化,只考虑了26个小写字母。
首先是节点的定义:
public class TrieNode {
public TrieNode[] children;
public char data;
public int freq;
public TrieNode() {
//因为有26个字母
children = new TrieNode[26];
freq = 0;
}
}
然后是Trie树的定义:
public class TrieTree {
private TrieNode root;
public TrieTree(){
root=new TrieNode();
}
...
}
2、插入
由于是26叉树,故可通过charArray[index]-‘a';来得知字符应该放在哪个孩子中。
public void insert(String word){
if(TextUtils.isEmpty(word)){
return;
}
insertNode(root,word.toCharArray(),0);
}
private static void insertNode(TrieNode rootNode,char[]charArray,int index){
int k=charArray[index]-'a';
if(k<0||k>25){
throw new RuntimeException("charArray[index] is not a alphabet!");
}
if(rootNode.children[k]==null){
rootNode.children[k]=new TrieNode();
rootNode.children[k].data=charArray[index];
}
if(index==charArray.length-1){
rootNode.children[k].freq++;
return;
}else{
insertNode(rootNode.children[k],charArray,index+1);
}
}
3、移除节点
移除操作中,需要对词频进行减一操作。
public void remove(String word){
if(TextUtils.isEmpty(word)){
return;
}
remove(root,word.toCharArray(),0);
}
private static void remove(TrieNode rootNode,char[]charArray,int index){
int k=charArray[index]-'a';
if(k<0||k>25){
throw new RuntimeException("charArray[index] is not a alphabet!");
}
if(rootNode.children[k]==null){
//it means we cannot find the word in this tree
return;
}
if(index==charArray.length-1&&rootNode.children[k].freq >0){
rootNode.children[k].freq--;
}
remove(rootNode.children[k],charArray,index+1);
}
4、查找频率
public int getFreq(String word){
if(TextUtils.isEmpty(word)){
return 0;
}
return getFreq(root,word.toCharArray(),0);
}
private static int getFreq(TrieNode rootNode,char[]charArray,int index){
int k=charArray[index]-'a';
if(k<0||k>25){
throw new RuntimeException("charArray[index] is not a alphabet!");
}
//it means the word is not in the tree
if(rootNode.children[k]==null){
return 0;
}
if(index==charArray.length-1){
return rootNode.children[k].freq;
}
return getFreq(rootNode.children[k],charArray,index+1);
}
5、测试
测试代码如下:
public static void test(){
TrieTree trieTree=new TrieTree();
String sourceStr="Democratic presumptive nominee Hillary Clintons campaign posed pounced on Trumps assertion that British term monetary turmoil might benefit his business venture in Scotland";
//String sourceStr="the that";
sourceStr=sourceStr.toLowerCase();
String[]strArray=sourceStr.split(" ");
for(String str:strArray){
trieTree.insert(str);
}
String sourceStr2="Every president is tested by world events But Donald Trump thinks about how is his golf resort can profit from that";
sourceStr2=sourceStr2.toLowerCase();
String[]strArray2=sourceStr2.split(" ");
for(String str:strArray2){
trieTree.insert(str);
}
BinaryTree.print("frequence of 'that':"+trieTree.getFreq("that"));
BinaryTree.print("\nfrequence of 'donald':"+trieTree.getFreq("donald"));
trieTree.remove("that");
BinaryTree.print("\nafter remove 'that' once,freq of 'that':"+trieTree.getFreq("that"));
trieTree.remove("that");
BinaryTree.print("\nafter remove 'that' twice,freq of 'that':"+trieTree.getFreq("that"));
trieTree.remove("donald");
BinaryTree.print("\nafter remove 'donald' once,freq of 'donald':"+trieTree.getFreq("donald"));
BinaryTree.reallyStartPrint();
}
测试结果如下:
总结


猜你喜欢
- 本文实例讲述了C#中实现一次执行多条带GO的sql语句。分享给大家供大家参考。具体如下:using System;using System.
- 在java里, 我们可以使用Executors.newFixedThreadPool 来创建线程池, 然后就可以不停的创建新任务,并用线程池
- 如何查看 Java 的字节码文件?在 Java 中,字节码文件.class实际上是二进制文件,并不能直接查看。要想查看,我们只能通过反编译对
- 1.任何一门编程语言均有相关数据类型。C#也不例外,其基本数据类型有int,short,long,float,double,string等。
- Android中ListView下拉刷新实现效果图:ListView中的下拉刷新是非常常见的,也是经常使用的,看到有很多同学想要,那我就整理
- 接收参数的方式:1.HttpServletRequest方式接收public ModelAndView test1(HttpServletR
- 分页问题是一个非常普遍的问题,开发者几乎都会遇到,这里不讨论具体如何分页,说明一下Web方式下分页的原理。首先是查询获得一个结果集(表现为查
- 示例:导入相关数据(Excel文件),相关的文件数据编辑好。XML文件配置再spring的xml文件中配置要上传文件的大小<!-- 上
- 一、内存池基础知识1、什么是内存池1.1 池化技术池化技术是计算机中的一种设计模式,主要是指:将程序中经常要使用的计算机资源预先申请出来,由
- 零碎记事距离上次发博客已经有一年半了,转眼间我也是从做图像研究到了做游戏开发,说起来看看前面的博文,本来就有前兆的东西呢(笑)......因
- 前言在这篇文章里,最后总结处,我说了会讲讲循环依赖中,其中一个类添加@Async有可能会导致注入失败而抛异常的情况,今天就分析一下。一、异常
- 1、前期准备需要在Manifest中添加相关权限<uses-permission android:name="android
- 摘要: 如何解决页面之间跳转时的黑屏问题呢?在默认情况下,Android应用程序启动时,会有一个黑屏的时期。原因是,首个activity会加
- 1 简介先来一张效果图TIM图片.gif上图中灰色的一块是ImageView控件,ImageView中的图片进行左右上下移动,以及双指缩放。
- 需要添加引用,System.Configuration;写系统配置文件: Configuration cfa =
- Logback TurboFilter实现日志级别等内容的动态修改可能看到这个标题,读者会问:要修改日志的级别,不是直接修改log.xxx就
- SpringAOP获取方法参数上的注解一、示例① 如下代码,自定义一个参数注解@Test,并将其使用到方法参数上,用于标注需要检验的参数/*
- Android EditText限制输入字符的方法总结最近项目要求限制密码输入的字符类型, 例如不能输入中文。 &nb
- Spring使用AOP完成统一结果封装起因:自己写项目的时候忍受不了每个方法都要写一个retrun Result.success();和 r
- 本文实例讲述了C#实现文件断点续传下载的方法。分享给大家供大家参考。具体实现方法如下:using System;using System.D