class Trie {
private Trie[] children; //定义children 类型为trie的数组 大小为26个
private boolean isEnd;
public Trie() {
children = new Trie[26];
isEnd = false;
}
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) { //遍历插入字符串的长度
char ch = word.charAt(i); //获取第i个字符串
int index = ch - 'a'; //获取索引值 如"abc" a=0
if (node.children[index] == null) {
node.children[index] = new Trie();// 如果对应的子树为空 则创建一个子数
}
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
Trie node = searchPrefix(word);
return node != null && node.isEnd; //精确查找需要最终节点的isEnd为真
}
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null; //模糊查找只需要最终节点不为空即可
}
private Trie searchPrefix(String prefix) {
Trie node = this; //node首先为根节点
for (int i = 0; i < prefix.length(); i++) {//遍历真个prefix的长度
char ch = prefix.charAt(i); //获取首个字符串"abc" a
int index = ch - 'a';//获取首个字符串"abc" a 的索引值
if (node.children[index] == null) {
return null; //如果首个children为空 直接返回null
}
node = node.children[index]; //否则继续获取子树的索引
}
return node; //最终返回最后的子数的节点node
}
}
![点击并拖拽以移动 wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==](https://img-blog.csdnimg.cn/2022010614353750119.gif)