Implement a trie with insert, search, and startsWith methods.
Example
insert("lintcode")
search("code") // return false
startsWith("lint") // return true
startsWith("linterror") // return false
insert("linterror")
search("lintcode) // return true
startsWith("linterror") // return true
/**
* Your Trie object will be instantiated and called as such:
* Trie trie = new Trie();
* trie.insert("lintcode");
* trie.search("lint"); will return false
* trie.startsWith("lint"); will return true
*/
class TrieNode {
TrieNode[] dict;
boolean end;
public TrieNode() {
dict = new TrieNode[26];
end = false;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode tmp = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(tmp.dict[c - 'a'] == null)
tmp.dict[c - 'a'] = new TrieNode();
tmp = tmp.dict[c - 'a'];
if(i == word.length() - 1) tmp.end = true;
}
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode tmp = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(tmp.dict[c - 'a'] == null) return false;
tmp = tmp.dict[c - 'a'];
}
return tmp.end;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode tmp = root;
for(int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if(tmp.dict[c - 'a'] == null) return false;
tmp = tmp.dict[c - 'a'];
}
return true;
}
}