-
Notifications
You must be signed in to change notification settings - Fork 1
/
leetcode-1268-searchSuggestionsSystem-4.js
104 lines (92 loc) · 2.46 KB
/
leetcode-1268-searchSuggestionsSystem-4.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
/**
* @param {string[]} products
* @param {string} searchWord
* @return {string[][]}
*/
// "mobile","mouse","moneypot","monitor","mousepad"
//
// m [,,,,,,,,,,,,*,,,,,,,,,,,,,,,]
// |
// o [,,,,,,,,,,,,,,*,,,,,,,,,,,,,]
// / | \
// b u n
// / | | \
// i s i e
// | | | |
// l * e t y
// | | | |
// * e p o p
// | | |
// a * r o
// | |
// * d * t
// "mobile","mouse","moneypot","monitor","mousepad"
// m: ["mobile","moneypot","monitor"]
// mo: ["mobile","moneypot","monitor"]
// mou: ["mouse","mousepad"]
// mous: ["mouse","mousepad"]
// mouse: ["mouse","mousepad"]
// create node for a Trie
class TrieNode {
constructor() {
this.isWord = false;
this.children = new Array(26);
}
}
// create a Trie
class Trie {
constructor() {
this.root = new TrieNode();
this.alphabet = "abcdefghijklmnopqrstuvwxyz";
}
// add all words to trie
insert(word) {
const a = this.alphabet;
let r = this.root;
for (let c of word) {
const i = a.indexOf(c);
if (!r.children[i]) r.children[i] = new TrieNode();
r = r.children[i];
}
r.isWord = true;
}
// use prefix to return an array of 3 first words
addWordsWith(prefix) {
const a = this.alphabet;
let r = this.root;
const result = [];
// go to the end of each prefix
for (let c of prefix) {
const i = a.indexOf(c);
if (!r.children[i]) return result;
r = r.children[i];
}
// use dfs to get the word from prefix's end
this.dfs(prefix, r, result);
return result;
}
// dfs prefix to get full words for addWordsWith
dfs(prefix, r, result) {
if (result.length === 3) return;
if (r.isWord) result.push(prefix);
const a = this.alphabet;
for (let i = 0; i < a.length; i++) {
if (r.children[i]) this.dfs(prefix + a[i], r.children[i], result);
}
}
}
//
// create function
var suggestedProducts = function (products, searchWord) {
const trie = new Trie();
for (let product of products) {
trie.insert(product);
}
const results = [];
let prefix = "";
for (let c of searchWord) {
prefix += c;
results.push(trie.addWordsWith(prefix));
}
return results;
};