解题思路:
class Trie {
private Trie[] children; // 存储子节点的数组
private boolean isEnd; // 记录是否为单词结尾
public Trie() {
children = new Trie[26]; // 数组大小为26,代表26个小写字母
isEnd = 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'; // 计算字母对应的索引
if (node.children[index] == null) {
node.children[index] = new Trie(); // 如果当前节点的子节点为空,创建一个新节点
}
node = node.children[index]; // 移动到子节点
}
node.isEnd = true; // 标记当前节点为单词结尾
}
public boolean search(String word) {
Trie node = searchPrefix(word); // 查找前缀
return node != null && node.isEnd; // 判断是否找到前缀并且是否为单词结尾
}
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null; // 判断是否找到前缀
}
private Trie searchPrefix(String prefix) {
Trie node = this; // 从根节点开始
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
int index = ch - 'a'; // 计算字母对应的索引
if (node.children[index] == null) {
return null; // 如果当前节点的子节点为空,返回null
}
node = node.children[index]; // 移动到子节点
}
return node; // 返回最后一个节点
}
}