-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtries.js
More file actions
78 lines (63 loc) · 1.29 KB
/
tries.js
File metadata and controls
78 lines (63 loc) · 1.29 KB
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
// 构建字典树函数版本
function buildTires (words) {
const root = {}
for (let word of words) {
// 当把每个单词遍历完后,指针要重新指回到最初的root节占
let node = root
for (const k of word) {
if (!node[k]) {
node[k] = {}
}
node = node[k]
}
// abcdef
node.end = true
}
return root
}
// 类版本
class BuildTires {
constructor () {
this.root = {}
}
add (word) {
let node = this.root
for (const k of word) {
if (!node[k]) {
node[k] = {}
}
node = node[k]
}
// 单条链结束标识
node.end = true
return this.root
}
}
const tires = new BuildTires()
tires.add('wfc')
tires.add('wac')
tires.add('fac')
console.log(JSON.stringify(tires.root))
// w
// f a
// c b
// const ret = buildTires(['wfc', 'wa'])
// console.log(JSON.stringify(ret))
// const stack = []
// function search(k) {
// stack.push(k)
// let idx = 0
// const len = stack.length
// let node = ret
// while (idx < len) {
// if (!node[stack[idx]]) return false
// node = node[stack[idx]]
// if (node.end) return true
// idx++
// }
// return false
// }
// console.log(search('w'))
// console.log(search('f'))
// console.log(search('c'))
// // [a, b, c, d]