Skip to content

Commit 843591e

Browse files
Create 208. 实现 Trie (前缀树).md
1 parent d43776a commit 843591e

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

Trie/208. 实现 Trie (前缀树).md

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#### 208. 实现 Trie (前缀树)
2+
3+
难度:中等
4+
5+
---
6+
7+
**Trie** (发音类似 "try")或者说 **前缀树** 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
8+
9+
请你实现 Trie 类:
10+
11+
* `Trie()` 初始化前缀树对象。
12+
* `void insert(String word)` 向前缀树中插入字符串 `word`
13+
* `boolean search(String word)` 如果字符串 `word` 在前缀树中,返回 `true`(即,在检索之前已经插入);否则,返回 `false`
14+
* `boolean startsWith(String prefix)` 如果之前已经插入的字符串 `word` 的前缀之一为 `prefix` ,返回 `true` ;否则,返回 `false`
15+
16+
**示例:**
17+
18+
```
19+
输入
20+
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
21+
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
22+
输出
23+
[null, null, true, false, true, null, true]
24+
25+
解释
26+
Trie trie = new Trie();
27+
trie.insert("apple");
28+
trie.search("apple"); // 返回 True
29+
trie.search("app"); // 返回 False
30+
trie.startsWith("app"); // 返回 True
31+
trie.insert("app");
32+
trie.search("app"); // 返回 True
33+
```
34+
35+
**提示:**
36+
37+
* `1 <= word.length, prefix.length <= 2000`
38+
* `word``prefix` 仅由小写英文字母组成
39+
* `insert``search``startsWith` 调用次数 **总计** 不超过 `3 * 10^4`
40+
41+
---
42+
43+
前缀树图解:
44+
45+
![](https://raw.githubusercontent.com/CompetitiveLin/ImageHostingService/picgo/imgs/202211191701591.png)
46+
47+
前缀树模板:
48+
49+
```java
50+
class Trie {
51+
private Trie[] children;
52+
private boolean isEnd;
53+
54+
public Trie(){
55+
children = new Trie[26];
56+
isEnd = false;
57+
}
58+
59+
public void insert(String word) {
60+
Trie temp = this;
61+
for(int i = 0; i < word.length(); i++){
62+
int index = word.charAt(i) - 'a';
63+
if(temp.children[index] == null){
64+
temp.children[index] = new Trie();
65+
}
66+
temp = temp.children[index];
67+
}
68+
temp.isEnd = true;
69+
}
70+
71+
public boolean search(String word) {
72+
Trie trie = searchPrefix(word);
73+
return trie != null && trie.isEnd;
74+
}
75+
76+
public boolean startsWith(String prefix) {
77+
return searchPrefix(prefix) != null;
78+
}
79+
80+
private Trie searchPrefix(String s){
81+
Trie temp = this;
82+
for(int i = 0; i < s.length(); i++){
83+
int index = s.charAt(i) - 'a';
84+
if(temp.children[index] == null) return null;
85+
temp = temp.children[index];
86+
}
87+
return temp;
88+
}
89+
}
90+
91+
/**
92+
* Your Trie object will be instantiated and called as such:
93+
* Trie obj = new Trie();
94+
* obj.insert(word);
95+
* boolean param_2 = obj.search(word);
96+
* boolean param_3 = obj.startsWith(prefix);
97+
*/
98+
```
99+

0 commit comments

Comments
 (0)