Skip to content

Commit 46a8a03

Browse files
authored
Update 1268-search-suggestions-system.js
1 parent 3c33190 commit 46a8a03

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

1268-search-suggestions-system.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,62 @@ const suggestedProducts = function(products, searchWord) {
3838
}
3939
return res
4040
};
41+
42+
// another
43+
44+
/**
45+
* @param {string[]} products
46+
* @param {string} searchWord
47+
* @return {string[][]}
48+
*/
49+
const suggestedProducts = function(products, searchWord) {
50+
const root = new Node()
51+
for(const str of products) {
52+
addProduct(str)
53+
}
54+
55+
const res = []
56+
57+
let cur = root
58+
for(const ch of searchWord) {
59+
const tmp = []
60+
if(cur == null) {
61+
res.push(tmp)
62+
continue
63+
}
64+
const map = cur.children.get(ch)
65+
if(map != null) {
66+
const arr = [...map.words]
67+
arr.sort()
68+
tmp.push(...arr.slice(0, 3))
69+
}
70+
71+
res.push(tmp)
72+
cur = map
73+
}
74+
75+
76+
return res
77+
78+
function addProduct(str) {
79+
let cur = root
80+
for(const ch of str) {
81+
let next = cur.children.get(ch)
82+
if(next == null) {
83+
next = new Node()
84+
cur.children.set(ch, next)
85+
}
86+
next.words.add(str)
87+
cur = next
88+
}
89+
cur.isWord = true
90+
}
91+
};
92+
93+
class Node {
94+
constructor() {
95+
this.children = new Map()
96+
this.words = new Set()
97+
this.isWord = false
98+
}
99+
}

0 commit comments

Comments
 (0)