-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
46 lines (41 loc) · 1.01 KB
/
index.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
/**
* Problem: https://leetcode.com/problems/replace-words/description/
*/
/**
* @param {string[]} dict
* @param {string} sentence
* @return {string}
*/
var replaceWords = function(dict, sentence) {
const TreeNode = function(val) {
this.val = val;
this.isLeaf = false;
this.children = {};
};
const root = new TreeNode(null);
for (let word of dict) {
let tmp = root;
for (let i = 0; i < word.length; i++) {
const letter = word[i];
const node = tmp.children[letter] || new TreeNode(letter);
if (i === word.length - 1) node.isLeaf = true;
tmp.children[letter] = node;
tmp = node;
}
}
return sentence.split(' ').map(word => {
let tmp = root, wordRoot = '';
for (let i = 0; i < word.length; i++) {
const letter = word[i];
const node = tmp.children[letter];
if (node) {
wordRoot += letter;
if (node.isLeaf) return wordRoot;
tmp = node;
} else {
break;
}
}
return word;
}).join(' ');
};