class Trie {
static class TrieNode{
TrieNode children[];
boolean isWord;
TrieNode(){
children = new TrieNode[26];
}
}
/** Initialize your data structure here. */
private TrieNode root;
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = root;
for(char c : word.toCharArray()){
if(node.children[c - 'a'] == null){
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = root;
for(char c : word.toCharArray()){
if(node.children[c - 'a'] == null){
return false;
}
node = node.children[c - 'a'];
}
return node.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = root;
for(char c : prefix.toCharArray()){
if(node.children[c - 'a'] == null){
return false;
}
node = node.children[c - 'a'];
}
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);
*/
实现前缀树java实现
最新推荐文章于 2024-06-05 15:33:07 发布