208.Implement Trie (Prefix Tree)
Implement a trie withinsert,search, andstartsWithmethods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
class Trie {
class TrieNode {
int count;
List<String> list;
TrieNode[] children;
TrieNode() {
count = 0;
list = new ArrayList<>();
children = new TrieNode[26];
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
if (word == null) return;
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.count++;
}
node.list.add(word);
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if (word == null) return false;
TrieNode node = root;
for (char c : word.toCharArray()) {
node = node.children[c-'a'];
if (node == null || node.count == 0) return false;
}
return node != null && node.list.contains(word);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if (prefix == null) return false;
TrieNode node = root;
for (char c : prefix.toCharArray()) {
node = node.children[c-'a'];
if (node == null || node.count == 0) return false;
}
return node != null && node.count != 0;
}
}
/**
* 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);
*/