class TreeNode {
char val;
TreeNode[] next;
boolean isEnd;
public TreeNode(){
this.next = new TreeNode[26];
}
}
class Trie {
public TreeNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TreeNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TreeNode node= root;
for(int i = 0; i < word.length(); i++){
int index = word.charAt(i) - 'a';
if(node.next[index] == null)
node.next[index] = new TreeNode();
node = node.next[index];
}
node.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TreeNode node = root;
for(int i = 0; i < word.length(); i++){
int index = word.charAt(i) - 'a';
if(node.next[index] != null){
node = node.next[index];
}else
return false;
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TreeNode node = root;
for(int i = 0; i < prefix.length(); i++){
int index = prefix.charAt(i) - 'a';
if(node.next[index] != null){
node = node.next[index];
}else
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);
*/
【刷题】Leetcode 208. Implement Trie (Prefix Tree)
最新推荐文章于 2022-10-10 23:49:16 发布