class Trie {
class trieNode{
trieNode[] next;
boolean isEnd;
public trieNode(){
next=new trieNode[26];
isEnd=false;
}
}
trieNode root;
/** Initialize your data structure here. */
public Trie() {
root=new trieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
trieNode cur=root;
char[] chars=word.toCharArray();
for(int i=0;i<chars.length;i++){
int index=chars[i]-'a';
if(cur.next[index]==null){
cur.next[index]=new trieNode();
}
cur=cur.next[index];
}
cur.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
char[] chars=word.toCharArray();
trieNode cur=root;
for(int i=0;i<chars.length;i++){
int index=chars[i]-'a';
if(cur.next[index]==null){
return false;
}
cur=cur.next[index];
}
return cur.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
char[] chars=prefix.toCharArray();
trieNode cur=root;
for(int i=0;i<chars.length;i++){
int index=chars[i]-'a';
if(cur.next[index]==null){
return false;
}
cur=cur.next[index];
}
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);
*/
前缀树2.前缀树实现
最新推荐文章于 2023-02-09 09:32:54 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)