Implement a trie withinsert
,search
, andstartsWith
methods.
Note:
You may assume that all inputs are consist of lowercase lettersa-z
.
tag: Trie
class Trie {
private class TrieNode{
TrieNode[] children;
boolean isWord;
public TrieNode(){
children = new TrieNode[26];
isWord = false;
}
public void insert(String word, int index){
if (index == word.length()){
this.isWord = true;
return;
}
int pos = word.charAt(index) - 'a';
if (children[pos] == null){
children[pos] = new TrieNode();
}
children[pos].insert(word, index + 1);
}
public TrieNode search(String word, int index){
if (index == word.length()){
return this;
}
int pos = word.charAt(index) - 'a';
if (children[pos] == null){
return null;
}
return children[pos].search(word, index + 1);
}
public boolean startsWith(String prefix, int index){
if (index == prefix.length()){
return true;
}
int pos = prefix.charAt(index) - 'a';
if (children[pos] == null) return false;
return children[pos].startsWith(prefix, index + 1);
}
}
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
root.insert(word, 0);
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode found = root.search(word, 0);
return found != null && found.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return root.startsWith(prefix, 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);
*/