代码集-字典树

//字典树
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];
	}
}


你可能感兴趣的:(代码集)