leetcode208 Implement Trie (Prefix Tree)--java实现

本文详细介绍了Trie树的概念、基本性质及其在文本词频统计中的应用。通过Java代码实现,展示了如何利用Trie树进行高效查询与存储大量字符串。

Trie,又称单词查找树或键树,是一种树形结构。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

Trie树的三个基本性质:

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

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

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

java程序如下:

import java.util.LinkedList;

class TrieNode{
	// Initialize your data structure here.
	char content; // the character in the node
	boolean isEnd; // whether the end of the words
	int count; // the number of words sharing this character
	LinkedList<TrieNode> childList; // the child list 每个节点的孩子节点集合
	public TrieNode(char c){
		childList = new LinkedList<TrieNode>();
		isEnd=false;
		content=c;
		count=0;
	}
	public TrieNode subNode(char c){
		if(childList!=null){
			for(TrieNode eachChild:childList){
				if(eachChild.content==c){
					return eachChild;
				}
			}
		}
		return null;
	}
}

public class Trie {
	private TrieNode root;
	public Trie(){
		root = new TrieNode(' ');
	}
	// Inserts a word into the trie.
	public void insert(String word){
		if(search(word)==true)return;
		TrieNode current=root;
		for(int i=0;i<word.length();i++){
			TrieNode child=current.subNode(word.charAt(i));
			if(child!=null){
				current=child;
			}else{
				current.childList.add(new TrieNode(word.charAt(i)));
				current=current.subNode(word.charAt(i));
			}
			current.count++;
		}
		current.isEnd=true;
	}
	// Returns if the word is in the trie.
	public boolean search(String word){
		TrieNode 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;
		}
	}
	// Returns if there is any word in the trie
    // that starts with the given prefix.
	public boolean startsWith(String prefix) {
		TrieNode current = root;
		for(int i=0;i<prefix.length();i++){
			if(current.subNode(prefix.charAt(i))==null){
				return false;
			}else{
				current=current.subNode(prefix.charAt(i));
			}
		}
		return true;
    }
}
用心仔细看,真的没有那么困难。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值