代码理解见注释!!!非常简单易懂!!
import java.util.HashMap;
public class DictTreeTest {
private TreeNode root;
public DictTreeTest(){
root = new TreeNode();
}
class TreeNode{
private int path;//该字母被使用次数
private int end;//结束字母为0 表示该单词没有记录或者已经被删除
private HashMap<Character,TreeNode> map;//子节点
public TreeNode(){
this.path = 0;
this.end = 0;
this.map = new HashMap<>();
}
}
//search
public boolean search(String word){
if(word == null)
return false;
char[] chars = word.toCharArray();
TreeNode node = root;
for(int i=0;i<chars.length;i++){//循环遍历字符串所有字符 全部存在才可以
if(node.map.get(chars[i]) == null){
return false;
}
node = node.map.get(chars[i]);
}
return node.end != 0;//判断结束字符是否为0
}
//add
public void add(String word){
if(word == null)
return;
char[] chars = word.toCharArray();
TreeNode node = root;
for(int i=0;i<chars.length;i++){//循环遍历字符串所有字符 若某字符不存在 则新建子节点
if(node.map.get(chars[i]) == null){
node.map.put(chars[i],new TreeNode());
}
node = node.map.get(chars[i]);
node.path++;//该字符的使用次数加一
}
node.end++;//该字符串的结尾字符数加一
}
//delete
public void delete(String word){
if(search(word)){//判断字符是否存在 存在继续!
char[] chars = word.toCharArray();
TreeNode node = root;
for(int i=0;i<chars.length;i++){//循环遍历字符串所有字符 一次删除
if(node.map.get(chars[i]).path-- == 1){//单词的使用次数减一 若该单词只有一次使用记录 则直接置空该单词的子节点并返回
node.map.put(chars[i],new TreeNode());
return;
}
node = node.map.get(chars[i]);
}
node.end--;//单词的结尾字符数减一
}
}
public static void main(String[] args){
DictTreeTest dictTree = new DictTreeTest();
String str1 = "zhugege";
String str2 = "zhugege";
dictTree.add(str1);
dictTree.add(str2);
System.out.println(dictTree.search("zhu"));
System.out.println(dictTree.search("zhugege"));
dictTree.delete("zhugege");
System.out.println(dictTree.search("zhugege"));
dictTree.delete("zhugege");
System.out.println(dictTree.search("zhugege"));
}
}
测试结果图: