-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtrie.js
382 lines (347 loc) · 8.88 KB
/
trie.js
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import treeLogo from "../imgs/tree.svg";
const cppCode = `
struct TrieNode {
TrieNode *children[26];
bool isEnd;
TrieNode(bool end=false) {
isEnd = end;
memset(children, 0, sizeof(children));
}
};
class Trie {
private:
TrieNode *root;
TrieNode* findString(string word) {
TrieNode *p = root;
for (size_t i=0; i<word.size(); i++) {
int index = word[i] - 'a';
if(p->children[index] == nullptr)
return nullptr;
p = p->children[index];
}
return p;
}
void clear(TrieNode *root) {
for (size_t i = 0; i < 26; i ++)
if (root->children[i])
clear(root->children[i]);
delete root;
}
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
~Trie() {
clear(root);
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p = root;
for(size_t i=0; i<word.size(); i++) {
int index = word[i] - 'a';
if (!p->children[index])
p->children[index] = new TrieNode();
p = p->children[index];
}
p->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p = findString(word);
return p != nullptr && p->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *p = findString(prefix);
return p != nullptr;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
`;
const goCode = `
type Node struct {
isWord bool
next map[byte]*Node
}
func NewNode(isWord bool) *Node {
return &Node{isWord: isWord, next: make(map[byte]*Node)}
}
type Trie struct {
root *Node
}
//func NewTrie() *Trie {
// return &Trie{root: NewNode(false)}
//}
/** Initialize your data structure here. */
func Constructor() Trie {
return Trie{root: NewNode(false)}
}
/** Inserts a word into the trie. */
func (t *Trie) Insert(word string) {
cur := t.root
for i := 0; i < len(word); i++ {
c := word[i]
_, ok := cur.next[c]
if !ok { //
cur.next[c] = NewNode(false)
}
cur = cur.next[c]
}
if !cur.isWord { // 标记为单词
cur.isWord = true
}
}
/** Returns if the word is in the trie. */
func (t *Trie) Search(word string) bool {
cur := t.root
for i := 0; i < len(word); i++ {
c := word[i]
v, ok := cur.next[c]
if !ok {
return false
}
cur = v
}
return cur.isWord
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func (t *Trie) StartsWith(prefix string) bool {
cur := t.root
for i := 0; i < len(prefix); i++ {
c := prefix[i]
v,ok := cur.next[c]
if !ok {
return false
}
cur = v
}
return true
}
`;
const javaCode = `
class Trie {
class TireNode {
boolean isEnd = false;
TireNode[] next = new TireNode[26];
TireNode() {}
}
private TireNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TireNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TireNode node = root;
for (char ch : word.toCharArray()) {
if (node.next[ch-'a'] == null) {
node.next[ch-'a'] = new TireNode();
}
node = node.next[ch-'a'];
}
node.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TireNode node = root;
for (char ch : word.toCharArray()) {
if (node.next[ch-'a'] == null) return false;
node = node.next[ch-'a'];
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TireNode node = root;
for (char ch : prefix.toCharArray()) {
if (node.next[ch-'a'] == null) return false;
node = node.next[ch-'a'];
}
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);
*/
`;
export default {
title: "前缀树",
logo: treeLogo,
list: [
{
text: "标准前缀树",
problems: [
{
title: "208.实现 Trie (前缀树)",
id: "implement-trie-prefix-tree",
},
{
title: "211.添加与搜索单词 - 数据结构设计",
id: "add-and-search-word-data-structure-design",
},
{
id: "word-search-ii",
title: "212.单词搜索 II",
},
{
id: "concatenated-words",
title: "472.连接词",
},
{
title: "648. 单词替换",
id: "replace-words",
},
{
id: "short-encoding-of-words",
title: "820.单词的压缩编码",
},
{
title: "1032.字符流",
id: "stream-of-characters",
},
],
codes: [
{
language: "py",
text: `
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.Trie = {}
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
curr = self.Trie
for w in word:
if w not in curr:
curr[w] = {}
curr = curr[w]
curr['#'] = 1
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
curr = self.Trie
for i, w in enumerate(word):
if w == '.':
wizards = []
for k in curr.keys():
if k == '#':
continue
wizards.append(self.search(word[:i] + k + word[i + 1:]))
return any(wizards)
if w not in curr:
return False
curr = curr[w]
return "#" in curr
`,
},
{
language: "js",
text: `
function TrieNode(val) {
this.val = val;
this.children = [];
this.isWord = false;
}
function computeIndex(c) {
return c.charCodeAt(0) - "a".charCodeAt(0);
}
/**
* Initialize your data structure here.
*/
var Trie = function() {
this.root = new TrieNode(null);
};
/**
* Inserts a word into the trie.
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
let ws = this.root;
for (let i = 0; i < word.length; i++) {
const c = word[i];
const current = computeIndex(c);
if (!ws.children[current]) {
ws.children[current] = new TrieNode(c);
}
ws = ws.children[current];
}
ws.isWord = true;
};
/**
* Returns if the word is in the trie.
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
let ws = this.root;
for (let i = 0; i < word.length; i++) {
const c = word[i];
const current = computeIndex(c);
if (!ws.children[current]) return false;
ws = ws.children[current];
}
return ws.isWord;
};
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function(prefix) {
let ws = this.root;
for (let i = 0; i < prefix.length; i++) {
const c = prefix[i];
const current = computeIndex(c);
if (!ws.children[current]) return false;
ws = ws.children[current];
}
return true;
};
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/
`,
},
{
language: "cpp",
text: cppCode,
},
{
language: "go",
text: goCode,
},
{
language: "java",
text: javaCode,
},
],
},
],
link:
"https://github.com/azl397985856/leetcode/blob/master/thinkings/trie.md",
};