Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods.
Note: You may assume that all inputs are consist of lowercase letters a-z.
Solution
class TrieNode {
String val;
Map<Character, TrieNode> map;
public TrieNode() {
val = null;
map = new HashMap<>();
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
insert(word, 0, root);
}
public void insert(String word, int d, TrieNode current) {
if (word.length() == d) {
current.val = word;
return;
}
char currentChar = word.charAt(d);
TrieNode next = null;
if (current.map.containsKey(currentChar)) {
next = current.map.get(currentChar);
} else {
next = new TrieNode();
current.map.put(currentChar, next);
}
insert(word, d + 1, next);
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode runner = root;
for (int i = 0; i < word.length(); i++) {
runner = runner.map.get(word.charAt(i));
if (runner == null) {
return false;
}
}
return runner.val == null ? false : runner.val.equals(word);
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode runner = root;
for (int i = 0; i < prefix.length(); i++) {
runner = runner.map.get(prefix.charAt(i));
if (runner == null) {
return false;
}
}
return true;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");