代码集-字典树

//字典树
public class DirectoryTree {
	//根结点
	private DirTreeNode root=new DirTreeNode();
	public static void main(String[] args) {
		DirectoryTree tree=new DirectoryTree();
		tree.insert("Hello");
		tree.insert("KeepThinking");
		tree.insert("Hi");
		System.out.println(tree.search("Keep"));
		tree.insert("Keep");
		tree.insert("Keep");
		tree.insert("Keep");
		System.out.println(tree.search("Keep"));
		System.out.println(tree.search("keepThinking"));
	}
	//插入
	public  void insert(String word){
		word=word.toLowerCase();
		//父结点
		DirTreeNode preNode=root;
		//下一个结点
		DirTreeNode nextNode=null;
		char[] words=word.toCharArray();
		int length=words.length;
		for(int i=0;i<length;i++){
			nextNode=preNode.childs[words[i]-'a'];
			if(nextNode==null){
				nextNode=new DirTreeNode();
				preNode.childs[words[i]-'a']=nextNode;
			}
			preNode=nextNode;
		}
		if(preNode!=root){
			preNode.time++;
		}
	}
	//查找,返回所查单词在当前树中一共存储了多少次
	public  int search(String word){
		word=word.toLowerCase();
		//父结点
		DirTreeNode preNode=root;
		//下一个结点
		DirTreeNode nextNode=null;
		
		char[] words=word.toCharArray();
		int length=words.length;
		for(int i=0;i<length;i++){
			nextNode=preNode.childs[words[i]-'a'];
			if(nextNode==null)return 0;
			preNode=nextNode;
		}
		return preNode.time;
	}
}
//字典树结点
class DirTreeNode{
	//以该结点作为最后结点的单词的次数
	public int time;
	//子结点集合
	public DirTreeNode[] childs;
	//初始化
	public DirTreeNode(){
		//二十六个字母,不区分大小写,如果要区分,开32或者128的数组
		childs=new DirTreeNode[26];
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值