手撸 算法 java 字典树算法

 字典树,又称单词查找树,是一个典型的一对多的字符串匹配算法。“一”指的是一个模式串,“多”指的是多个模板串。字典树经常被用来统计、排序和保存大量的字符串。它利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较;并可以减少存储量;

package tire;
import java.util.TreeMap;
public class Tire {

	private class Node {
		public boolean isWord = false;
		TreeMap<Character, Node> next;

		public Node() {
			next = new TreeMap<>();
		}
	}

	public Node root;
	public int size;

	public Tire() {
		root = new Node();
		size = 0;
	}

	public void add(String words) {//添加一个节点
		add(root, words, 0);
	}

	public void add(Node preNode, String words, int index) {
		if (words.length() == index) {// 递归到底的情况
			if (preNode.isWord == false)
				size++;
			preNode.isWord = true;
			return;
		}

		// 判断当前是否已经存在;
		Character c = words.charAt(index);
		// 当前根是否已经存在指向下一个字符的节点
		if (preNode.next.get(c) == null) {
			preNode.next.put(c, new Node());
		}

		add(preNode.next.get(c), words, index+1);// 不存在的话添加一个新节点
	}

	public boolean searchChar(String words) {
		Node node = root;
		for (int i = 0; i < words.length(); i++) {
			Character c = words.charAt(i);
			if (null == node.next.get(c)) {
				return false;
			}  

			node = node.next.get(c);
		}

		return node.isWord;
	}

	public boolean containsPreFix(String words)
	{
		Node node = root;
		int len = words.length();
		for(int i =0;i<len;i++)
		{
			Character c = words.charAt(i);
			node = node.next.get(c);
			if(null ==node)
			{
				return false;
			}
			
		}
		return true;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Tire tire = new Tire();
		tire.add("apple");
		tire.add("hello");
		
		tire.add("quickly");
		
		System.out.println("word search:"+tire.searchChar("word"));
		System.out.println("word search:"+tire.searchChar("hello"));
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恋恋西风

up up up

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值