-
Notifications
You must be signed in to change notification settings - Fork 42
/
solution.js
50 lines (48 loc) · 1.23 KB
/
solution.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
/**
* @param {string} s
* @param {string[]} dict
* @return {string}
*/
var addBoldTag = function (s, dict) {
const result = [];
let index = 0;
while (index < s.length) {
const len = match(index);
if (len === 0) {
result.push(s[index++]);
continue;
}
let end = index + len;
const start = index++;
while (index <= end) {
const len = match(index);
end = Math.max(end, index + len);
if (index === end && len === 0) {
break;
}
index++;
}
result.push(`<b>${s.slice(start, end)}</b>`);
}
function match (start) {
let maxLength = 0;
for (let i = 0; i < dict.length; i++) {
if (startWith(start, dict[i])) {
maxLength = Math.max(maxLength, dict[i].length);
}
}
return maxLength;
}
function startWith (start, word) {
if (start + word.length > s.length) {
return false;
}
for (let i = 0; i < word.length; i++) {
if (word[i] !== s[start + i]) {
return false;
}
}
return true;
}
return result.join('');
};