简介

Trie树,又称为前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。

它的主要特点如下:

根节点不包含字符,除根节点外的每一个节点都只包含一个字符。

从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。

每个节点的所有子节点包含的字符都不相同。

如下是一棵典型的Trie树:

Trie的来源是Retrieval,它常用于前缀匹配和词频统计。可能有人要说了,词频统计简单啊,一个hash或者一个堆就可以搞定,但问题来了,如果内存有限呢?还能这么 玩吗?所以这里我们就可以用trie树来压缩下空间,因为公共前缀都是用一个节点保存的。

1、定义

这里为了简化,只考虑了26个小写字母。

首先是节点的定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class TrieNode {
 
 public TrieNode[] children;
 
 public char data;
 
 public int freq;
 
 public TrieNode() {
 //因为有26个字母
 children = new TrieNode[26];
 freq = 0;
 }
 
}

然后是Trie树的定义:

1
2
3
4
5
6
7
8
9
10
11
public class TrieTree {
 
 private TrieNode root;
 
 public TrieTree(){
 root=new TrieNode();
 }
 
 ...
 
}

2、插入

由于是26叉树,故可通过charArray[index]-‘a';来得知字符应该放在哪个孩子中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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、移除节点

移除操作中,需要对词频进行减一操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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、查找频率

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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、测试

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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();
 
 
}

测试结果如下:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

Trie树(字典树)的介绍及Java实现的更多相关文章

  1. AC自动机——1 Trie树(字典树)介绍

    AC自动机——1 Trie树(字典树)介绍 2013年10月15日 23:56:45 阅读数:2375 之前,我们介绍了Kmp算法,其实,他就是一种单模式匹配.当要检查一篇文章中是否有某些敏感词,这其 ...

  2. 剑指Offer——Trie树(字典树)

    剑指Offer--Trie树(字典树) Trie树 Trie树,即字典树,又称单词查找树或键树,是一种树形结构,是一种的单词.对于每一个单词,我们要判断他出没出现过,如果出现了,求第一次出现在第几个位 ...

  3. Trie(字典树)

    没时间整理了,老吕又讲课了@ @ 概念 Trie即字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种,典型应用是统计和排序大量的字符串(不限于字符串) Trie字典树主要用于存储字符串, ...

  4. 9-11-Trie树/字典树/前缀树-查找-第9章-《数据结构》课本源码-严蔚敏吴伟民版

    课本源码部分 第9章  查找 - Trie树/字典树/前缀树(键树) ——<数据结构>-严蔚敏.吴伟民版        源码使用说明  链接☛☛☛ <数据结构-C语言版>(严蔚 ...

  5. Trie树|字典树(字符串排序)

    有时,我们会碰到对字符串的排序,若采用一些经典的排序算法,则时间复杂度一般为O(n*lgn),但若采用Trie树,则时间复杂度仅为O(n). Trie树又名字典树,从字面意思即可理解,这种树的结构像英 ...

  6. Trie(前缀树/字典树)及其应用

    Trie,又经常叫前缀树,字典树等等.它有很多变种,如后缀树,Radix Tree/Trie,PATRICIA tree,以及bitwise版本的crit-bit tree.当然很多名字的意义其实有交 ...

  7. [LintCode] Implement Trie 实现字典树

    Implement a trie with insert, search, and startsWith methods. Have you met this question in a real i ...

  8. Trie - leetcode [字典树/前缀树]

    208. Implement Trie (Prefix Tree) 字母的字典树每个节点要定义一个大小为26的子节点指针数组,然后用一个标志符用来记录到当前位置为止是否为一个词,初始化的时候讲26个子 ...

  9. Trie树/字典树题目(2017今日头条笔试题:异或)

    /* 本程序说明: [编程题] 异或 时间限制:1秒 空间限制:32768K 给定整数m以及n个数字A1,A2,..An,将数列A中所有元素两两异或,共能得到n(n-1)/2个结果,请求出这些结果中大 ...

随机推荐

  1. iOS UIView Class Translation

    类 UIView 一个管理屏幕上矩形区域内容的对象.   概述 Views 是你应用的用户界面最基础的组成部分.UIView类定义了对于所有 views 的共有的行为.一个 view 对象在它的边界矩 ...

  2. 饮冰三年-人工智能-Python-26 Django 学生管理系统

    背景:创建一个简单的学生管理系统,熟悉增删改查操作 一:创建一个Django项目(http://www.cnblogs.com/wupeiqi/articles/6216618.html) 1:创建实 ...

  3. maven问题解决:提示maven依赖包缺失,但是去文件夹下找确实有这个包

    出现问题:提示maven依赖包缺失,但是去文件夹下找确实有这个包. (我的操作就是:删除文件夹中的jar.重新update,) 搞了好多遍,工具总是提示错误信息,没办法,请求大神 操作大概过程: 1  ...

  4. ERROR Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)

    1.之前搭建的kafka,过了好久,去启动kafka,发现报如下下面的错误,有错误就要解决了. 然后参考:https://blog.csdn.net/hello_world_qwp/article/d ...

  5. Cookie和Session的原理和异同

    Cookie和Session的原理和异同 原理: cookie: 1.创建Cookie 当用户第一次浏览某个使用Cookie的网站时,该网站的服务器就进行如下工作: ①该用户生成一个唯一的识别码(Co ...

  6. springboot引用dubbo的方式

    1.以此种接口依赖的方式 这种相当于将其他模块的服务先拿过来dubbo自己在本模块中进行注入,此时可以直接用Spring的@Autowired注解引用 ,这种情况下本模块的扫描dubbo是所引用的模块 ...

  7. 小程序API

    基础: wx.canIUse(string)    boolean wx.canIUse(string schema)   判断小程序的API,回调,参数,组件等是否在当前版本可用. 参数说明 ${A ...

  8. babel分析

    现在都用 ES6 新语法以及 ES7 新特性来写应用了,但是浏览器和相关的环境还不能友好的支持,需要用到 Babel 转码器来转换成 ES5 的代码 相信大家都看到过如下的名词: babel-pres ...

  9. 什么是nrm

    什么是nrm nrm 是一个 npm 源管理器,允许你快速地在 npm 源间切换. 安装nrm 在命令行执行命令,npm install -g nrm,全局安装nrm. 使用 执行命令nrm ls查看 ...

  10. 用DFS求连通块(种子填充)

    [问题] 输入一个m行n列的字符矩阵,统计字符“@”组成多少个八连块.如果两个字符“@”所在的格子相邻(横.竖或者对角线方向),就说它们属于同一个八连块.例如,图6-9中有两个八连块. 图6-9 [分 ...