码迷,mamicode.com
首页 > 编程语言 > 详细

Java Tire树

时间:2015-11-15 06:08:27      阅读:1011      评论:0      收藏:0      [点我收藏+]

标签:

Tire树,又叫字典树,主要是用来查找单词,词频统计的.

老规矩,直接上代码.

package tireTree;

public class TireTree {
	TireNode root;

	public TireTree(TireNode root) {
		this.root = root;
	}

	private void insertElement(TireNode root, String word) {
		if (word == null || word.isEmpty())
			return;
		char[] elements = word.toCharArray();
		int index = elements[0] - ‘a‘;
		if (root.getNode()[index] == null) {
			root.getNode()[index] = new TireNode();
			root.getNode()[index].setElement(elements[0]);
		}
		if (word.length() == 0)
			return;
		insertElement(root.getNode()[index], word.substring(1));
	}

	private boolean searchWord(TireNode root, String word) {
		if (word == null || word.isEmpty())
			return false;
		TireNode p = root;
		int index = 0;
		while (p != null && index < word.length()) {
			int k = word.charAt(index) - ‘a‘;
			if (root.getNode()[k] != null) {
				if (index == word.length() - 1) {
					root.getNode()[k].setFreq(root.getNode()[k].getFreq() + 1);
					return true;
				} else {
					root = root.getNode()[k];
					index++;
				}
			} else {
				return false;
			}
		}
		return false;
	}

	public static void main(String[] args) {
		TireNode root = new TireNode();
		TireTree tree = new TireTree(root);
		String context = "My Name is Tom,What is your name?My name is Jenny.";
		String target = "tom";
		for (String word : TireTree.transContext(context)) {
			tree.insertElement(root, word);
		}
		System.out.println(tree.searchWord(root, target));
	}

	public static String[] transContext(String context) {
		String c = context.toLowerCase();
		c = c.replaceAll("[,?!.]", " ");
		c = c.substring(0, context.length() - 1);
		return c.split(" ");
	}
}

class TireNode {
	private TireNode[] node;
	private int freq;
	private char element;

	public void setElement(char element) {
		this.element = element;
	}

	public TireNode() {
		node = new TireNode[26];
		freq = 0;
	}

	public TireNode[] getNode() {
		return node;
	}

	public int getFreq() {
		return freq;
	}

	public char getElement() {
		return element;
	}

	public void setNode(TireNode[] node) {
		this.node = node;
	}

	public void setFreq(int freq) {
		this.freq = freq;
	}

}

  

Java Tire树

标签:

原文地址:http://www.cnblogs.com/dick159/p/4965995.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!