208. 实现Trie(前缀树)
题目
描述:
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补全和拼写检查。
请你实现 Trie 类:
Trie()初始化前缀树对象。void insert(String word)向前缀树中插入字符串word。boolean search(String word)如果字符串word在前缀树中,返回true(即,在检索之前已经插入);否则,返回false。boolean startsWith(String prefix)如果之前已经插入的字符串word的前缀之一为prefix,返回true;否则,返回false。
示例:
输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"][[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]输出
[null, null, true, false, true, null, true]解释
1 2 3 4 5 6 7
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // 返回 True trie.search("app"); // 返回 False trie.startsWith("app"); // 返回 True trie.insert("app"); trie.search("app"); // 返回 True
提示:
1 <= word.length, prefix.length <= 2000word和prefix仅由小写英文字母组成insert、search和startsWith调用次数 总计 不超过3 * 10^4次
题解
用字符路径共享前缀
Trie 的根节点表示空前缀,从根沿字符分支走出的路径表示一个前缀。例如插入 apple,会依次建立或复用 a、p、p、l、e 五条分支。再插入 app 时,前三个字符的路径已经存在,可以直接复用。
每个节点保存 children[26] 和 isEnd。题目字符都是小写英文字母,通过 c - 'a' 映射到下标 0 到 25;子节点为空表示没有对应的下一字符。isEnd 表示到这个位置是否存在一个完整单词,不能用“是否还有孩子”代替,因为 app 可以同时是单词和 apple 的前缀。
插入、查单词和查前缀
insert 从根开始逐字符前进,缺少分支就创建节点,全部字符走完后才设置 isEnd = true。重复插入同一单词只会再次设置标记,不会创建另一条相同路径。
searchPrefix 只检查路径,缺少任一字符就返回 null,否则返回路径终点。search 要求终点存在且 isEnd 为真;startsWith 只要求终点存在。
例如只插入 apple 时,startsWith("app") 为真,search("app") 为假;再插入 app 后,后一个结果也变为真,且原来的 apple 仍然存在。查询不会创建节点或改变单词标记。
复杂度
一次操作最多沿长度为 $L$ 的路径前进,时间为 $O(L)$。设所有插入单词的字符总数为 $K$,实际节点数至多为 $K+1$;每个节点包含固定的 26 个引用,总存储为 $O(K+1)$。查询使用迭代,只需 $O(1)$ 额外工作空间。
完整示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class Main {
static class Trie {
private class TrieNode {
private TrieNode[] children;
private boolean isEnd;
public TrieNode() {
children = new TrieNode[26];
isEnd = false;
}
}
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
private TrieNode searchPrefix(String prefix) {
TrieNode node = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
int index = c - 'a';
if (node.children[index] == null) {
return null;
}
node = node.children[index];
}
return node;
}
}
public static void main(String[] args) {
Trie trie = new Trie();
System.out.println("insert(\"apple\")");
trie.insert("apple");
System.out.println("search(\"apple\") = " + trie.search("apple"));
System.out.println("search(\"app\") = " + trie.search("app"));
System.out.println("startsWith(\"app\") = " + trie.startsWith("app"));
System.out.println("insert(\"app\")");
trie.insert("app");
System.out.println("search(\"app\") = " + trie.search("app"));
System.out.println("search(\"banana\") = " + trie.search("banana"));
System.out.println("insert(\"banana\")");
trie.insert("banana");
System.out.println("search(\"banana\") = " + trie.search("banana"));
System.out.println("startsWith(\"ban\") = " + trie.startsWith("ban"));
}
}
运行结果(OpenJDK 21.0.12):
1
2
3
4
5
6
7
8
9
10
insert("apple")
search("apple") = true
search("app") = false
startsWith("app") = true
insert("app")
search("app") = true
search("banana") = false
insert("banana")
search("banana") = true
startsWith("ban") = true
