public class Trie {
/**
* Initialize your data structure here.
*/
boolean isword;
HashMap next;
public Trie() {
isword = false;
next = new HashMap();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
Trie tp = this;
for (int i = 0; i < word.length(); i++) {
if (tp.next.containsKey(word.charAt(i))) {
tp = tp.next.get(word.charAt(i));
} else {
Trie t = new Trie();
tp.next.put(word.charAt(i), t);
tp = t;
}
}
tp.isword = true;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
Trie tp = this;
for (int i = 0; i < word.length(); i++) {
if (tp.next.containsKey(word.charAt(i))) {
tp = tp.next.get(word.charAt(i));
} else {
return false;
}
}
return tp.isword;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
Trie tp = this;
for (int i = 0; i < prefix.length(); i++) {
if (tp.next.containsKey(prefix.charAt(i))) {
tp = tp.next.get(prefix.charAt(i));
} else {
return false;
}
}
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);
*/