更新
我觉得更好的是官方题解说的方法。
以下是我根据它写的。
https://blog.csdn.net/weixin_42970433/article/details/120852839
题目
https://leetcode-cn.com/problems/implement-trie-prefix-tree/
参考题解:https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/208-shi-xian-trie-qian-zhui-shu-bao-gua-insert-sea/
class Trie {
class TrieNode{
public int path;
public int end;
public HashMap<Character,TrieNode> next;
public TrieNode(){
path=0;
end=0;
next=new HashMap<>();
}
}
private TrieNode root;
public Trie() {
root=new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
if(word==null||word.length()==0)
return;
TrieNode node=root;
for(int i=0;i<word.length();i++){
Character c=(Character)word.charAt(i);
if(!node.next.containsKey(c)){
node.next.put(c,new TrieNode());
}
node=node.next.get(c);
node.path++;
}
node.end++;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if(word==null||word.length()==0)
return false;
TrieNode node=root;
for(int i=0;i<word.length();i++){
Character c=(Character)word.charAt(i);
if(!node.next.containsKey(c)){
return false;
}
node=node.next.get(c);
}
if(node.end==0)
return false;
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if(prefix==null||prefix.length()==0)
return false;
TrieNode node=root;
for(int i=0;i<prefix.length();i++){
Character c=(Character)prefix.charAt(i);
if(!node.next.containsKey(c)){
return false;
}
node=node.next.get(c);
}
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);
*/
/*
public void delete(String word){
if(word == null || word.equals("") || !search(word)) return ;
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if(--node.next.get(ch).path == 0){
node.next.remove(ch);
return;
}
node = node.next.get(ch);
}
node.end--;
}
*/
public void delete(String word){
if(word == null || word.equals("") || !search(word)) return ;
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if(--node.next.get(ch).path == 0){
node.next.remove(ch);
return;
}
node = node.next.get(ch);
}
node.end--;
}