class TrieNode {
// Initialize your data structure here.public HashMap<Character,TrieNode> map;
public boolean flag = false;
publicTrieNode() {
map = new HashMap<Character,TrieNode>();
}
}
publicclass Trie {
private TrieNode root;
publicTrie() {
root = new TrieNode();
}
// Inserts a word into the trie.publicvoidinsert(String word) {
TrieNode node = root;
int index = 0;
while (index < word.length() && node.map.containsKey(word.charAt(index))) {
node = node.map.get(word.charAt(index));
index++;
}
while (index < word.length()) {
node.map.put(word.charAt(index), new TrieNode());
node = node.map.get(word.charAt(index));
index++;
}
node.flag = true;
}
// Returns if the word is in the trie.public boolean search(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char tmp = word.charAt(i);
if (!node.map.containsKey(tmp)) returnfalse;
node = node.map.get(word.charAt(i));
}
return node.flag;
}
// Returns if there is any word in the trie// that starts with the given prefix.public boolean startsWith(String prefix) {
TrieNode node = root;
for (int i = 0; i < prefix.length(); i++) {
char tmp = prefix.charAt(i);
if (!node.map.containsKey(tmp)) returnfalse;
node = node.map.get(prefix.charAt(i));
}
returntrue;
}
}