Implement a trie with insert, search, and startsWith methods.
实现字典树的插入、搜索和startsWith方法。
题解:字典树就是多叉树,区别是多叉树除了指向子节点的数组,还保存的是当前节点值。而字典树保存的是标明自己是否是isEnd,true表示根节点开始到自己是一个字符值。
如下代码所示:
class TreeNode {
//多叉树保存的是当前节点值
T value;
TreeNode[] next;
}
class TrieNode {
//字典树保存的是表明自己是否是一串值的结束位置
bool isEnd;
TrieNode[] next;
}
保存小写字母的字典树代码如下:
class Trie{
class TrieNode {
boolean isEnd;
TrieNode[] next;
TrieNode() {
next = new TrieNode[26];
isEnd = false;
}
void insert(String word) {
TrieNode node = this;
for(char ch : word.toCharArray()) {
if(node.next[ch - 'a'] == null) {
node.next[ch - 'a'] = new TrieNode();
}
node = node.next[ch - 'a'];
}
node.isEnd = true;
}
boolean search(String word){
TrieNode node = this;
for(char ch : word.toCharArray()) {
node = node.next[ch - 'a'];
if(node == null) {
return false;
}
}
return node.isEnd;
}
boolean startsWith(String prefix) {
TrieNode node = this;
for(char ch : prefix.toCharArray()) {
node = node.next[ch - 'a'];
if(node == null){
return false;
}
}
return true;
}
}
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
root.insert(word);
}
public boolean search(String word) {
return root.search(word);
}
public boolean startsWith(String prefix) {
return root.startsWith(prefix);
}
}
/**
* 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);
*/