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