【参考:前缀树算法模板秒杀 5 道算法题__微信公众号】 比较复杂,了解即可
中等
208. 实现 Trie
【参考:208. 实现 Trie - 力扣(LeetCode)】
方法不唯一
【参考:Leetcode 208. 实现 Trie 字典树_哔哩哔哩_bilibili】
【参考:Leetcode 208. 实现 Trie - itdef - 博客园】
代码参考 【参考:Trie Tree 的实现 🌳 - 实现 Trie (前缀树) - 力扣(LeetCode)】
class Trie {
class TrieNode{
boolean isEnd; //该结点是否是一个串的结束
TrieNode[] next=new TrieNode[26]; //字母映射表
}
TrieNode root; // 根节点不存储数据
public Trie() {
root=new TrieNode();
}
public void insert(String word) {
TrieNode p=root;
char[] cs=word.toCharArray();
for(char c:cs){
int index=c-'a';
if(p.next[index]==null){ // 到末尾了
p.next[index]=new TrieNode(); // 插入新节点
p=p.next[index]; // p指向新节点
}else{
p=p.next[index]; // p指向下一个节点
}
}
p.isEnd=true;// 标记结束
}
public boolean search(String word) {
TrieNode p=root;
char[] cs=word.toCharArray();
for(char c:cs){
int index=c-'a';
p=p.next[index]; // p指向下一个节点
if(p==null){ // 到末尾了
return false;
}
}
// 此时p指向word的最后一个字母
return p.isEnd;// 看word的最后一个字母是不是串的结尾
}
public boolean startsWith(String prefix) {
TrieNode p=root;
char[] cs=prefix.toCharArray();
for(char c:cs){
int index=c-'a';
p=p.next[index]; // p指向下一个节点
if(p==null){ // 到末尾了
return false;
}
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/