TrieTree字典树

 Trie树,又称为单词查找树,字典树,键树。是哈希树的变种。
 应用与统计和排序大量字符串,所以经常用于搜索引擎系统用于文本词频系统。
 优点:最大限度的减少无谓的字符串的比较,查找效率比哈希表高。
 基本性质:
 1)根节点不包含字符,除根外每个节点只包含一个字符。
  2)从根节点到某一节点,路径上经过的字符连起来,为该结点对应的字符串。
 3)每个结点包含的所有子结点都不相同。

 注:设置标志,表示该字符是否为结束字符。不一定是最后字符。例如does,其中do中的o就有标志。

本片中给出TrieTree树的结构定义和插入,查询,删除操作。

一、Trie树的结构定义

import java.util.LinkedList;

/**
 * trietree的结点定义形式
 * */
public class TrieTreeNode {
	char content;//节点中包含的字符
	boolean isEnd;//是否为单词的最后一个字符
	int count;//包含这个字符的单词个数
	LinkedList<TrieTreeNode> childList;//子结点序列
	
	//初始化
	public TrieTreeNode(char c){
		childList = new LinkedList<TrieTreeNode>();
		isEnd = false;
		content = c;
		count = 0;
	}
	
	//trietree中是否包含字符c结点,包含则返回该字符,否则返回空
	public TrieTreeNode subNode(char c){
		if(childList != null){
			for (TrieTreeNode trieTreeNode : childList) {
				if(trieTreeNode.content == c){
					return trieTreeNode;
				}
			}
		}
		return null;
	}	
}
二、Trie树的插入,查找和删除结点的方法

public class TrieTree {
	public static void main(String[] args) {
		//测试代码
		TrieTree trie = new TrieTree();
		trie.insert("zengxiao");
		trie.insert("zengxiaoqiang");
		trie.insert("haohaoxuexi");
		System.out.println(trie.search("zengxiao"));
		System.out.println(trie.search("zeng"));
		trie.delete("zengxiao");
		System.out.println(trie.search("zengxiao"));
 	}

	private TrieTreeNode root;
	public TrieTree(){
		root = new TrieTreeNode(' ');
	}
	
	/**
	 * 将字符串的字符插入到trietree中
	 * @param word
	 */
	public void insert(String word){
		if(search(word) == true){
			return;
		}
		TrieTreeNode current = root;
		for(int i=0; i<word.length(); i++){
			TrieTreeNode child = current.subNode(word.charAt(i));//生成一个结点
			if(child != null){
				current = child;
			}else{
				current.childList.add(new TrieTreeNode(word.charAt(i)));
				current = current.subNode(word.charAt(i));
			}
			current.count++;
		}
		current.isEnd = true;
	}
	
	/**
	 * 查找字符串是否在trietree中
	 * @param word
	 * @return
	 */
	public boolean search(String word){
		TrieTreeNode current = root;
		
		for(int i=0; i<word.length(); i++){
			if(current.subNode(word.charAt(i)) == null){
				return false;
			}else{
				current = current.subNode(word.charAt(i));
			}
		}
		if(current.isEnd == true){
			return true;
		}else{
			return false;
		}
	}
	public void delete(String word){
		if(search(word) == false){//没有找到字符串word则不用做任何操作
			return ;
		}
		TrieTreeNode current = root;
		for (char c : word.toCharArray()) {
			TrieTreeNode child = current.subNode(c);
			if(child.count == 1){
				current.childList.remove(child);
				return;
			}else{
				child.count--;
				current = child;
			}
		}
		current.isEnd = false;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值