class Trie {
private Trie[] children;
private boolean isEnd;
public Trie() {
children = new Trie[26];
isEnd = false;
}
// word work
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;
}
node = node.children[index];
}
return node;
}
}
实现前缀树-leetcode 208
最新推荐文章于 2025-11-30 23:49:47 发布
这个博客详细介绍了Trie数据结构的实现,包括如何插入单词、查找单词以及检查字符串前缀是否存在。Trie是一种高效的数据结构,常用于存储和检索字符串,特别是用于自动补全和拼写检查等应用。
563

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



