java
Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补全和拼写检查。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
前缀树是N叉树的一种特殊形式。通常来说,一个前缀树是用来存储字符串的。前缀树的每一个节点代表一个字符串(前缀)。每一个节点会有多个子节点,通往不同子节点的路径上有着不同的字符。子节点代表的字符串是由节点本身的原始字符串,以及通往该子节点路径上所有的字符组成的。
java
class Trie {
private Trie[] children;
private boolean isEnd;
public Trie() {
children = new Trie[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;
}
node = node.children[index];
}
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);
*/
数据结构
children数组:每个Trie节点包含一个长度为26的数组,对应英文小写字母。数组中的每个元素表示下一个字符的节点(如children[0]对应字母'a')。
isEnd标志:布尔值,标记当前节点是否为某个单词的结尾。
构造函数
Trie():初始化时创建一个空的子节点数组,并将isEnd设为false。根节点本身不存储字符,其子节点对应单词的首字母。
方法解析
- 插入单词(insert方法)
功能:将单词插入Trie中。
步骤:
从根节点开始遍历。
对每个字符计算索引(如ch - 'a'),若对应子节点不存在则创建新节点。
移动到子节点,继续处理下一个字符。
遍历结束后,将最后一个节点的isEnd设为true,标记单词结束。
示例:插入"apple"时,会依次创建a→p→p→l→e的路径,并在e节点设置isEnd=true。
- 搜索单词(search方法)
功能:检查单词是否存在于Trie中。
步骤:
调用searchPrefix查找单词的路径。
若路径存在且最后一个节点的isEnd为true,则返回true;否则返回false。
示例:搜索"apple"时,若路径存在且e节点的isEnd=true,返回true。
- 前缀匹配(startsWith方法)
功能:检查是否存在以给定前缀开头的单词。
步骤:
调用searchPrefix查找前缀路径。
若路径存在(无论isEnd状态),返回true。
示例:前缀"app"存在(如单词"apple"),返回true。
- 辅助方法(searchPrefix)
功能:内部方法,定位前缀的最后一个节点。
步骤:
从根节点开始,逐字符遍历前缀。
若中途遇到子节点不存在,返回null。
遍历完成后返回当前节点。
关键点:此方法为search和startsWith提供复用逻辑。