java实现的Trie树数据结构
近期在学习的时候,常常看到使用Trie树数据结构来解决这个问题。比方“ 有一个1G大小的一个文件。里面每一行是一个词。词的大小不超过16字节,内存大小限制是1M。
返回频数最高的100个词。
”
 该怎样解决? 有一种方案就是使用Trie树加 排序实现 。
什么是Trie 树呢?也就是常说的字典树,网上对此讲得也非常多,简单补充一下个人理解: 它实际上相当于把单词的公共部分给拎出来。这样一层一层往上拎直到得到每一个节点都是不可分的最小单元!
比方网上一个样例
一组单词,inn, int, at, age, adv, ant, 我们能够得到以下的Trie:

这里的节点上存的是一个单词,实际上。每一个节点走过的路径就是该节点代表的单词!其他不多扯了~~~
Trie树有什么优点呢
本文不是讲理论。仅仅是给出用java自己实现的Trie树数据结构,当中实现了插入、查找、遍历、单词联想(找公共前缀)等基本功能,
 其他功能大家能够自己加入~~~~
package com.algorithms; import java.util.HashMap;
import java.util.Map; public class Trie_Tree{ /**
* 内部节点类
* @author "zhshl"
* @date 2014-10-14
*
*/
private class Node{
private int dumpli_num;////该字串的反复数目, 该属性统计反复次数的时候实用,取值为0、1、2、3、4、5……
private int prefix_num;///以该字串为前缀的字串数。 应该包含该字串本身。。! 。!
private Node childs[];////此处用数组实现,当然也能够map或list实现以节省空间
private boolean isLeaf;///是否为单词节点
public Node(){
dumpli_num=0;
prefix_num=0;
isLeaf=false;
childs=new Node[26];
}
} private Node root;///树根
public Trie_Tree(){
///初始化trie 树
root=new Node();
} /**
* 插入字串。用循环取代迭代实现
* @param words
*/
public void insert(String words){
insert(this.root, words);
}
/**
* 插入字串,用循环取代迭代实现
* @param root
* @param words
*/
private void insert(Node root,String words){
words=words.toLowerCase();////转化为小写
char[] chrs=words.toCharArray(); for(int i=0,length=chrs.length; i<length; i++){
///用相对于a字母的值作为下标索引,也隐式地记录了该字母的值
int index=chrs[i]-'a';
if(root.childs[index]!=null){
////已经存在了,该子节点prefix_num++
root.childs[index].prefix_num++;
}else{
///假设不存在
root.childs[index]=new Node();
root.childs[index].prefix_num++;
} ///假设到了字串结尾,则做标记
if(i==length-1){
root.childs[index].isLeaf=true;
root.childs[index].dumpli_num++;
}
///root指向子节点,继续处理
root=root.childs[index];
} } /**
* 遍历Trie树,查找全部的words以及出现次数
* @return HashMap<String, Integer> map
*/
public HashMap<String,Integer> getAllWords(){
// HashMap<String, Integer> map=new HashMap<String, Integer>(); return preTraversal(this.root, "");
} /**
* 前序遍历。。。
* @param root 子树根节点
* @param prefixs 查询到该节点前所遍历过的前缀
* @return
*/
private HashMap<String,Integer> preTraversal(Node root,String prefixs){
HashMap<String, Integer> map=new HashMap<String, Integer>(); if(root!=null){ if(root.isLeaf==true){
////当前即为一个单词
map.put(prefixs, root.dumpli_num);
} for(int i=0,length=root.childs.length; i<length;i++){
if(root.childs[i]!=null){
char ch=(char) (i+'a');
////递归调用前序遍历
String tempStr=prefixs+ch;
map.putAll(preTraversal(root.childs[i], tempStr));
}
}
} return map;
} /**
* 推断某字串是否在字典树中
* @param word
* @return true if exists ,otherwise false
*/
public boolean isExist(String word){
return search(this.root, word);
}
/**
* 查询某字串是否在字典树中
* @param word
* @return true if exists ,otherwise false
*/
private boolean search(Node root,String word){
char[] chs=word.toLowerCase().toCharArray();
for(int i=0,length=chs.length; i<length;i++){
int index=chs[i]-'a';
if(root.childs[index]==null){
///假设不存在,则查找失败
return false;
}
root=root.childs[index];
} return true;
} /**
* 得到以某字串为前缀的字串集。包含字串本身。 相似单词输入法的联想功能
* @param prefix 字串前缀
* @return 字串集以及出现次数,假设不存在则返回null
*/
public HashMap<String, Integer> getWordsForPrefix(String prefix){
return getWordsForPrefix(this.root, prefix);
}
/**
* 得到以某字串为前缀的字串集。包含字串本身。
* @param root
* @param prefix
* @return 字串集以及出现次数
*/
private HashMap<String, Integer> getWordsForPrefix(Node root,String prefix){
HashMap<String, Integer> map=new HashMap<String, Integer>();
char[] chrs=prefix.toLowerCase().toCharArray();
////
for(int i=0, length=chrs.length; i<length; i++){ int index=chrs[i]-'a';
if(root.childs[index]==null){
return null;
} root=root.childs[index]; }
///结果包含该前缀本身
///此处利用之前的前序搜索方法进行搜索
return preTraversal(root, prefix);
} }
下面是測试类:
package com.algorithm.test;
import java.util.HashMap;
import com.algorithms.Trie_Tree;
public class Trie_Test {
	 public static void main(String args[])  //Just used for test
	    {
	    Trie_Tree trie = new Trie_Tree();
	    trie.insert("I");
	    trie.insert("Love");
	    trie.insert("China");
	    trie.insert("China");
	    trie.insert("China");
	    trie.insert("China");
	    trie.insert("China");
	    trie.insert("xiaoliang");
	    trie.insert("xiaoliang");
	    trie.insert("man");
	    trie.insert("handsome");
	    trie.insert("love");
	    trie.insert("chinaha");
	    trie.insert("her");
	    trie.insert("know");
	    HashMap<String,Integer> map=trie.getAllWords();
	    for(String key:map.keySet()){
	    	System.out.println(key+" 出现: "+ map.get(key)+"次");
	    }
	    map=trie.getWordsForPrefix("chin");
	    System.out.println("\n\n包括chin(包括本身)前缀的单词及出现次数:");
	    for(String key:map.keySet()){
	    	System.out.println(key+" 出现: "+ map.get(key)+"次");
	    }
	    if(trie.isExist("xiaoming")==false){
	    	System.out.println("\n\n字典树中不存在:xiaoming ");
	    }
	    }
}
chinaha 出现: 1次
her 出现: 1次
handsome 出现: 1次
know 出现: 1次
man 出现: 1次
xiaoliang 出现: 2次
i 出现: 1次
china 出现: 5次
包括chin(包括本身)前缀的单词及出现次数:
chinaha 出现: 1次
china 出现: 5次
字典树中不存在:xiaoming
总结:在实现的时候。主要是想好怎样设计每一个节点的结构,这里针对单词总共26个,使用了一个字符数组来记录。事实上全然能够用list或其它的容器来实现。这样也就能够容纳更复杂的对象了!另外一个方面就是。一个节点的prefix_num属性实际上是指到该节点经过的路径(也就是字串)的反复数。而不是到该节点的反复数(由于一个节点的child域并非指某个单词,这样prefix_num对该节点本身没意义)。最后,遍历使用了前序遍历的递归实现。相信对学过一点数据结构的不难。。。
java实现的Trie树数据结构的更多相关文章
- trie树--详解
		
文章作者:yx_th000 文章来源:Cherish_yimi (http://www.cnblogs.com/cherish_yimi/) 转载请注明,谢谢合作.关键词:trie trie树 数据结 ...
 - 数据结构与算法—Trie树
		
Trie,又经常叫前缀树,字典树等等.它有很多变种,如后缀树,Radix Tree/Trie,PATRICIA tree,以及bitwise版本的crit-bit tree.当然很多名字的意义其实有交 ...
 - [数据结构] 2.3 Trie树
		
抱歉更新晚了,看了几天三体,2333,我们继续数据结构之旅. 一.什么是Tire树? Tire树有很多名字:字典树.单词查找树. 故名思意,它就是一本”字典“,当我们查找"word" ...
 - 数据结构《16》----自动补齐实现《一》----Trie 树
		
1. 简述 Trie 树是一种高效的字符串查找的数据结构.可用于搜索引擎中词频统计,自动补齐等. 在一个Trie 树中插入.查找某个单词的时间复杂度是 O(len), len是单词的长度. 如果采用平 ...
 - Trie 树 及Java实现
		
来源于英文“retrieval”. Trie树就是字符树,其核心思想就是空间换时间. 举个简单的例子. 给你100000个长度不超过10的单词.对于每一个单词,我们要判断他出没出现过,如果出现 ...
 - [转]数据结构之Trie树
		
1. 概述 Trie树,又称字典树,单词查找树或者前缀树,是一种用于快速检索的多叉树结构,如英文字母的字典树是一个26叉树,数字的字典树是一个10叉树. Trie一词来自retrieve,发音为/tr ...
 - 数据结构之Trie树
		
1. 概述 Trie树,又称字典树,单词查找树或者前缀树,是一种用于快速检索的多叉树结构,如英文字母的字典树是一个26叉树,数字的字典树是一个10叉树. Trie一词来自retrieve,发音为/tr ...
 - 双数组Trie树(DoubleArrayTrie)Java实现
		
http://www.hankcs.com/program/java/%E5%8F%8C%E6%95%B0%E7%BB%84trie%E6%A0%91doublearraytriejava%E5%AE ...
 - 【数据结构】Trie树
		
数据结构--Trie树 概念 Trie树,又称字典树.前缀树,是一种树形结构,是一种哈希树的变种.典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计 ...
 
随机推荐
- J2SE知识点摘记(二十四)
			
覆写hashCode() 在明白了HashMap具有哪些功能,以及实现原理后,了解如何写一个hashCode()方法就更有意义了.当然,在HashMap中存取一个键值对涉及到的另外一个方法为equa ...
 - openssl编译(VC6.0)
			
官网:http://www.openssl.org/ 得到源码: git clone https://github.com/openssl/openssl 一.用vc编译器编译: 1.下载nasm: ...
 - Qt for Windows:使用WinPcap开发高性能UDP服务器
			
首先介绍一下WinPcap WinPcap是Windows下一个网络库,性能极其强悍而且能够接收各种包. 大名鼎鼎的WireShark就是基于这个库开发的. 那么这个库性能到底有多高呢. 我测试了UD ...
 - Day3_字符串操作与正则表达式
			
本节课的主要内容有:字符串的格式化.连接与分割.比较.匹配和替换.使用正则表达式 字符串的格式化: 去除空格:trim() 使用html格式化:nl2br() 替换‘\n’为‘<br /> ...
 - nodejs项目中的路由写法
			
//两种路由写法,一种封装成函数,返回结果,此种方法可以传递参数, "use strict"; var _ = require("lodash"); var e ...
 - 项目代码摘抄,dot的用法之1
			
function searchTags() { var list = $('#tags-list-select option:selected').val(); console.log(list); ...
 - 链表-remove duplicates from sorted list
			
struct ListNode* deleteDuplicates(struct ListNode* head) { struct ListNode *p=head; if(!head) return ...
 - bootstrap2.3.2常用标签的使用
			
<!DOCTYPE html> <html lang="zh_CN"> <head> <title>Bootstrap 101 Te ...
 - APP应用的发展趋势
			
PhoneGap 是什么 PhoneGap 是一个用基于HTML,CSS 和JavaScript 的,创建移动跨平台移动应用程序的快速开发框架.它使开发者能够利用iPhone,Android,Palm ...
 - intellj idea 如何设置类头注释和方法注释
			
intellj idea 如何设置类头注释和方法注释 intellj idea的强大之处就不多说了,相信每个用过它的人都会体会到,但是我们也会被他的复杂搞的晕头转向,尤其刚从ecl ...