前言
LeetCode 208 字典树
每个节点的只是布尔类型,每个节点都有26个孩子节点,节点的值为在单词最后一个字母处为true,其他时候为false;如图所示单词[sea,sells,she]在字典树中保存如下:(红色节点的值为true)
1.定义数据结构
boolean val;
Trie[] children;
public Trie() {
val=false;
children=new Trie[26];
}
2.插入单词
public void insert(String word) {
Trie root=this;
for(int i=0;i<word.length();i++){
int index=word.charAt(i)-'a';
//节点为null时,新建节点
if(root.children[index]==null){
root.children[index]=new Trie();
}
root=root.children[index];
}
//在单词结束的节点将值赋true
root.val=true;
}
3.搜寻是否存在单词
public Trie searchprefix(String word){
Trie root=this;
for(int i=0;i<word.length();i++){
int index=word.charAt(i)-'a';
if(root.children[i]==null){
return null;
}
root=root.children[index];
}
return root;
}
4.完整代码
class Trie {
boolean val;
Trie[] children;
public Trie() {
val=false;
children=new Trie[26];
}
public void insert(String word) {
Trie root=this;
for(int i=0;i<word.length();i++){
int index=word.charAt(i)-'a';
//节点为null时,新建节点
if(root.children[index]==null){
root.children[index]=new Trie();
}
root=root.children[index];
}
//在单词结束的节点将值赋true
root.val=true;
}
//查找单词
public boolean search(String word) {
Trie root=searchprefix(word);
return root!=null&&root.val;
}
//查找前缀
public boolean startsWith(String prefix) {
return searchprefix(prefix)!=null;
}
public Trie searchprefix(String word){
Trie root=this;
for(int i=0;i<word.length();i++){
int index=word.charAt(i)-'a';
if(root.children[i]==null){
return null;
}
root=root.children[index];
}
return root;
}
}