自己实现的字典树版本。带详细注释
package leetcode.LC;
class TrieNode{
//4个参数设置
//以该节点字符为结尾的字符串数目
int end_num;
//以该节点作为前缀字符的个数
int prefix_num;
//是否是叶子结点
boolean is_leaf;
//每个字符都含有26个字母可选
TrieNode sub_nodes[];
public TrieNode(){
end_num=0;
prefix_num=0;
is_leaf=false;
sub_nodes=new TrieNode[26];
}
}
public class trieTree {
//3个方法,插入、寻找、以某字符串开始的数量
//初始化树
public TrieNode root;
public trieTree(){
root=new TrieNode();
}
//插入一个字符串 关键!!
public void insert(String str){
//节点
TrieNode p=root;
//沿着字符串创建和处理树节点
for(int i=0;i<str.length();i++){
int ix=str.charAt(i)-'a';
//不存在则创建一个新的节点
if(p.sub_nodes[ix]==null){
p.sub_nodes[ix]=new TrieNode();
//有新的节点挂到p下面,所以p不是叶子结点了
p.is_leaf=false;
//新创建的节点是叶子结点
p.sub_nodes[ix].is_leaf=true;
}
//选择该节点
p=p.sub_nodes[ix];
//以该节点为前缀的数量+1
p.prefix_num++;
}
//以该节点为结尾的字符串数量+1
p.end_num++;
}
//查找某个字符串是否存在
public boolean search(String str){
TrieNode p=root;
for(int i=0;i<str.length();i++){
int ix=str.charAt(i)-'a';
//如果字符不存在,则说明不在trie树中
if(p.sub_nodes[ix]==null){
return false;
}
//
p=p.sub_nodes[ix];
}
//检查最后的字符是不是结尾,看以它为结尾的字符串数量即可
if(p.end_num>0){
return true;
}else{
return false;
}
}
//检查是否以str开头的字符串
public boolean start_with(String str){
//这个方法和search差不多
TrieNode p=root;
for(int i=0;i<str.length();i++){
int ix=str.charAt(i)-'a';
//如果字符不存在,则说明不在trie树中
if(p.sub_nodes[ix]==null){
return false;
}
p=p.sub_nodes[ix];
}
return true;
}
public static void main(String[] args) {
trieTree tree=new trieTree();
String words[] = {"a", "banana", "app", "appl", "ap", "apply", "apple"};
for(String i:words){
tree.insert(i);
}
System.out.println(tree.start_with("banan"));
}
}