-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
44 lines (39 loc) · 1.03 KB
/
solution.ts
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
function longestWord (words: string[]): string {
words.sort((a, b) => {
if (a.length !== b.length) {
return a.length - b.length;
}
return a < b ? 1 : -1;
});
let result = '';
const trie:any = {};
const search = (word:string, index:number, prev:any):boolean => {
while (index < word.length) {
if (prev.__end && search(word, index, trie)) {
return true;
}
if (!prev[word[index]]) {
return false;
}
prev = prev[word[index++]];
}
return !!prev.__end;
};
const insert = (word:string) => {
let prev = trie;
for (let i = 0; i < word.length; i++) {
if (!prev[word[i]]) {
prev[word[i]] = {};
}
prev = prev[word[i]];
}
prev.__end = true;
};
for (const word of words) {
if (search(word, 0, trie)) {
result = word;
}
insert(word);
}
return result;
}