题目
Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补全和拼写检查。
请你实现 Trie 类:
Trie()初始化前缀树对象。void insert(String word)向前缀树中插入字符串word。boolean search(String word)如果字符串word在前缀树中,返回true(即,在检索之前已经插入);否则,返回false。boolean startsWith(String prefix)如果之前已经插入的字符串word的前缀之一为prefix,返回true;否则,返回false。
链接
代码
class Trie {
// Trie树节点
private class TrieNode {
TrieNode[] children;
boolean isEnd;
public TrieNode() {
children = new TrieNode[26];
isEnd = false;
}
}
private TrieNode root;
// 初始化前缀树对象
public Trie() {
root = new TrieNode();
}
// 插入单词 word
public void insert(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
// 该字符子节点不存在,新建
if (cur.children[idx] == null) {
cur.children[idx] = new TrieNode();
}
cur = cur.children[idx];
}
// 单词结束,标记末尾
cur.isEnd = true;
}
// 搜索完整单词word,必须是插入过的完整单词
public boolean search(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (cur.children[idx] == null) {
return false; // 路径断了,不存在
}
cur = cur.children[idx];
}
// 路径走完,要看isEnd!只走到路径不算,必须是单词结尾
return cur.isEnd;
}
// 判断是否存在以prefix为前缀的单词
public boolean startsWith(String prefix) {
TrieNode cur = root;
for (char c : prefix.toCharArray()) {
int idx = c - 'a';
if (cur.children[idx] == null) {
return false;
}
cur = cur.children[idx];
}
// 只要前缀路径存在即可,不需要isEnd标记
return true;
}
}
