forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch Suggestions System.js
94 lines (73 loc) · 1.76 KB
/
Search Suggestions System.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
function TrieNode(key) {
this.key = key
this.parent = null
this.children = {}
this.end = false
this.getWord = function() {
let output = []
let node = this
while(node !== null) {
output.unshift(node.key)
node = node.parent
}
return output.join('')
}
}
function Trie() {
this.root = new TrieNode(null)
this.insert = function(word) {
let node = this.root
for (let i = 0; i < word.length; i++) {
if (!node.children[word[i]]) {
node.children[word[i]] = new TrieNode(word[i])
node.children[word[i]].parent = node
}
node = node.children[word[i]]
if (i === word.length - 1) {
node.end = true
}
}
}
this.findAllWords = function (node, arr) {
if (node.end) {
arr.unshift(node.getWord());
}
for (let child in node.children) {
this.findAllWords(node.children[child], arr);
}
}
this.find = function(prefix) {
let node = this.root
let output = []
for(let i = 0; i < prefix.length; i++) {
if (node.children[prefix[i]]) {
node = node.children[prefix[i]]
} else {
return output
}
}
this.findAllWords(node, output)
output.sort()
return output.slice(0, 3)
}
this.search = function(word) {
let node = this.root
let output = []
for (let i = 0; i < word.length; i++) {
output.push(this.find(word.substring(0, i + 1)))
}
return output
}
}
/**
* @param {string[]} products
* @param {string} searchWord
* @return {string[][]}
*/
var suggestedProducts = function(products, searchWord) {
let trie = new Trie()
for (let product of products) {
trie.insert(product)
}
return trie.search(searchWord)
};