Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
class TrieNode {
boolean isEnd;
TrieNode[] child;
public TrieNode() {
isEnd = true;
child = new TrieNode[26];
}
}
public class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode currNode = root;
for (char ch: word.toCharArray()) {
int id = ch - 'a';
if (currNode.child[id] == null) {
currNode.child[id] = new TrieNode();
currNode.child[id].isEnd = false;
}
currNode = currNode.child[id];
}
currNode.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
return match(word, 0);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return match(prefix, 1);
}
private boolean match(String word, int type) {
TrieNode currNode = root;
for (char ch: word.toCharArray()) {
int id = ch - 'a';
if (currNode.child[id] == null) {
return false;
}
currNode = currNode.child[id];
}
return type == 1? true: currNode.isEnd;
}
}
/**
* 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);
*/