class Trie {
private Trie[] children;
private boolean end;
public Trie() {
this.children = new Trie[26]; // 26个字母
this.end = false;
}
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a'; // todo 1. 获取和字符a的差值,然后children[差值] 存不存在
if (node.children[index] == null) { // todo 2. 如果trie.children【index】不存在,就新建一个
node.children[index] = new Trie();
}
node = node.children[index];
}
node.end = true;
}
public boolean search(String word) {
Trie node = searchWithPrefix(word);
return node != null && node.end;
}
public boolean startsWith(String prefix) {
return searchWithPrefix(prefix) != null;
}
// 查询prefix前缀的Tire树
private Trie searchWithPrefix(String prefix) {
Trie node = this;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
int index = ch - 'a'; // todo 1. 获取和字符a的差值,然后children[差值] 存不存在
if (node.children[index] == null) {
return null;
}
node = node.children[index]; // todo 2. node指向children[差值]
}
return node;
}
}
/**
* 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);
*/
在写这道算法的时候,如果对这个数据结构比较熟悉,其实不是很难