力扣 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

  • 提示:

    • 1 <= word.length, prefix.length <= 2000
    • wordprefix 仅由小写英文字母组成
    • insertsearchstartsWith 调用次数 总计 不超过 3 * 104

示例

例1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
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
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
class Trie {
// 字典树(前缀树)的根节点
Tree root;

// 进行操作的暂用节点
Tree temp;

// 当前字母在字典中的编号
int id;

/*
** 树节点类,每个树节点包括
** next:26个子节点
** isEnd:当前节点是否为一段字符串结尾
*/
class Tree {
Tree[] next = new Tree[26];
boolean isEnd = false;
}

/** Initialize your data structure here. */
public Trie() {
this.root = new Tree();
}

/** Inserts a word into the trie. */
public void insert(String word) {
temp = root;
for (int i = 0; i < word.length(); i++) {
id = word.charAt(i) - 'a';
if (temp.next[id] == null) {
temp.next[id] = new Tree();
}
temp = temp.next[id];
}
temp.isEnd = true;
}

/** Returns if the word is in the trie. */
public boolean search(String word) {
temp = root;
for (int i = 0; i < word.length(); i++) {
id = word.charAt(i) - 'a';
if (temp.next[id] == null) {
return false;
}
temp = temp.next[id];
}
return temp.isEnd;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
temp = root;
for (int i = 0; i < prefix.length(); i++) {
id = prefix.charAt(i) - 'a';
if (temp.next[id] == null) {
return false;
}
temp = temp.next[id];
}
return true;
}
}

/**
* 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);
*/

时间和空间效率都还行,可见此解法还比较适合此题;

image.png

总结

本题是今天的每日一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。