字典树
public class Tire {
//定义节点
private class Node{
boolean isWord=false;
TreeMap<Character,Node> next;
public Node() {
next=new TreeMap<>();
}
}
Node root;//根节点
int size;//节点个数
//构造方法
public Tire() {
root=new Node();
size=0;
}
//添加一个节点
public void add(String word) {
add(root,word,0);
}
private void add(Node preRoot,String words,int index) {
//递归到底的情况
if(index==words.length()) {
if(preRoot.isWord==false)
size++;
preRoot.isWord=true;
return;
}
Character c=words.charAt(index);
//当前根是否已经存在指向下一个字符的节点
if(preRoot.next.get(c)==null)
preRoot.next.put(c, new Node());//不存在的话添加一个新节点
add(preRoot.next.get(c),words,index+1);
}
//字典树中是否包含某个单词
public boolean contains(String word) {
Node cur=root;
for(int i=0;i<word.length();i++) {
char c=word.charAt(i);
if(cur.next.get(c)==null)
return false;
cur=cur.next.get(c);
}
return cur.isWord;
}
//查询是否包含某个前缀的单词
public boolean isPrefix(String prefix) {
Node cur=root;
for(int i=0;i<prefix.length();i++) {
if(cur.next.get(prefix.charAt(i))==null)
return false;
cur=cur.next.get(prefix.charAt(i));
}
return true;
}
//测试字典树
public static void main(String[] args) {
Tire t=new Tire();
t.add("apple");
t.add("apple");
t.add("applea");
t.add("appleaa");
System.out.println(t.contains("apple"));
System.out.println(t.isPrefix("app"));
System.out.println(t.size);
}
}