https://leetcode.cn/problems/implement-trie-prefix-tree/description/?envType=study-plan-v2&envId=top-interview-150
思路:我们使用一个树状结构来记录字典中每个单词的构成,你也可以先这么认为我们先构造了一层有26个节点的根(对应26个字母),然后如果进来一个单词apple,a对应的位置没有子节点,我们就给它生成1个子节点(包含26个Trie),然后往下走一层继续看p的位置有没有子节点,最后遍历完我们在e的子节点位置做上结束标记,代表这是一个单词的结束。
class Trie {
Trie[] prefixTree; // 用类似树状的结构记录单词的构成
boolean isEnd;
Trie() {
this.prefixTree = new Trie[26];
this.isEnd = isEnd;
}
public void insert(String word) {
Trie node = this; // 从根节点开始(也可以说是从第一层开始)
for(int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if(node.prefixTree[index] == null) { // 如果当前节点没有这个字母,则为这个节点新建一个节点
node.prefixTree[index] = new Trie();
}
// 如果当前节点有这个字母,则继续向下遍历
node = node.prefixTree[index];
}
node.isEnd = true; // 遍历完所有字母,将最后一个字母标记为单词的结尾
}
public boolean search(String word) {
Trie node = this;
for(int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if(node.prefixTree[index] == null) {
return false;
}
node = node.prefixTree[index];
}
return node.isEnd; // 遍历完所有字母,判断最后一个字母是否是单词的结尾
}
public boolean startsWith(String prefix) {
Trie node = this;
for(int i = 0; i < prefix.length(); i++) {
int index = prefix.charAt(i) - 'a';
if(node.prefixTree[index] == null) {
return false;
}
node = node.prefixTree[index];
}
return true; // 遍历完所有字母,就返回true
}
}
449

被折叠的 条评论
为什么被折叠?



