-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0758-bold-words-in-string.js
More file actions
47 lines (42 loc) · 1.28 KB
/
0758-bold-words-in-string.js
File metadata and controls
47 lines (42 loc) · 1.28 KB
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
/**
* Bold Words In String
* Time Complexity: O(W * L * M)
* Space Complexity: O(L)
*/
var boldWords = function (keywordList, targetString) {
const stringLength = targetString.length;
const boldMarker = new Array(stringLength).fill(false);
for (const currentWord of keywordList) {
let currentSearchPosition = targetString.indexOf(currentWord);
while (currentSearchPosition !== -1) {
const wordEndPosition = currentSearchPosition + currentWord.length;
for (
let boldIndex = currentSearchPosition;
boldIndex < wordEndPosition;
boldIndex++
) {
boldMarker[boldIndex] = true;
}
currentSearchPosition = targetString.indexOf(
currentWord,
currentSearchPosition + 1,
);
}
}
const outputCollector = [];
let isCurrentlyBold = false;
for (let charIndex = 0; charIndex < stringLength; charIndex++) {
if (boldMarker[charIndex] && !isCurrentlyBold) {
outputCollector.push("<b>");
isCurrentlyBold = true;
} else if (!boldMarker[charIndex] && isCurrentlyBold) {
outputCollector.push("</b>");
isCurrentlyBold = false;
}
outputCollector.push(targetString[charIndex]);
}
if (isCurrentlyBold) {
outputCollector.push("</b>");
}
return outputCollector.join("");
};