class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isExisted;
}
public class Trie {
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++) {
int c = word.charAt(i) - 'a';
if (node.children[c] == null) {
TrieNode child = new TrieNode();
node.children[c] = child;
node = child;
} else {
node = node.children[c];
}
}
node.isExisted = true;
}
// 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++) {
int c = word.charAt(i) - 'a';
if (node.children[c] == null) {
return false;
} else {
node = node.children[c];
}
}
return node.isExisted;
}
// 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++) {
int c = prefix.charAt(i) - 'a';
if (node.children[c] == null) {
return false;
} else {
node = node.children[c];
}
}
return true;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
Implement Trie (Prefix Tree)
最新推荐文章于 2021-09-10 14:48:52 发布