Skip to content

Commit e15f15f

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

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

1268-search-suggestions-system.js

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -46,40 +46,46 @@ const suggestedProducts = function(products, searchWord) {
4646
* @param {string} searchWord
4747
* @return {string[][]}
4848
*/
49-
const suggestedProducts = function(products, searchWord) {
49+
const suggestedProducts = function (products, searchWord) {
50+
products.sort()
5051
const root = new Node()
51-
for(const str of products) {
52+
for (const str of products) {
5253
addProduct(str)
5354
}
5455

5556
const res = []
5657

5758
let cur = root
58-
for(const ch of searchWord) {
59+
for (const ch of searchWord) {
5960
const tmp = []
60-
if(cur == null) {
61-
res.push(tmp)
62-
continue
61+
if (cur == null) {
62+
res.push(tmp)
63+
continue
6364
}
6465
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))
66+
if (map != null) {
67+
addThree(map.words.values(), tmp)
6968
}
7069

7170
res.push(tmp)
7271
cur = map
7372
}
7473

75-
7674
return res
77-
75+
76+
function addThree(it, arr) {
77+
78+
for(let i = 0; i < 3; i++) {
79+
const res = it.next()
80+
if(res.value) arr.push(res.value)
81+
}
82+
}
83+
7884
function addProduct(str) {
7985
let cur = root
80-
for(const ch of str) {
86+
for (const ch of str) {
8187
let next = cur.children.get(ch)
82-
if(next == null) {
88+
if (next == null) {
8389
next = new Node()
8490
cur.children.set(ch, next)
8591
}
@@ -88,12 +94,13 @@ const suggestedProducts = function(products, searchWord) {
8894
}
8995
cur.isWord = true
9096
}
91-
};
97+
}
9298

9399
class Node {
94100
constructor() {
95-
this.children = new Map()
96-
this.words = new Set()
97-
this.isWord = false
101+
this.children = new Map()
102+
this.words = new Set()
103+
this.isWord = false
98104
}
99105
}
106+

0 commit comments

Comments
 (0)