-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path1408.js
39 lines (35 loc) · 794 Bytes
/
1408.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
var stringMatching = function(words) {
let root = new Trie();
for (let word of words) {
for (let i = 0; i < word.length; i++) {
root.insert(word.substring(i));
}
}
let res = [];
for (let word of words) {
if (root.get(word)) res.push(word);
}
return res;
};
var Trie = function() {
this.val = 0;
this.next = {};
};
Trie.prototype.insert = function(word) {
let cur = this;
for (let c of word) {
if (!cur.next[c]) {
cur.next[c] = new Trie();
}
cur = cur.next[c];
cur.val++;
}
};
Trie.prototype.get = function(word) {
let cur = this;
for (let c of word) {
if (!cur.next[c]) return false;
cur = cur.next[c];
}
return cur.val > 1;
}