Skip to content

Commit f5eec81

Browse files
authored
Update 758-bold-words-in-string.js
1 parent 5bb4915 commit f5eec81

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

758-bold-words-in-string.js

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,26 @@
44
* @return {string}
55
*/
66
const boldWords = function (words, S) {
7-
const boldMap = new Array(S.length).fill(0)
8-
for (let i = 0; i < words.length; i++) {
9-
let match = -1
10-
while ((match = S.indexOf(words[i], match + 1)) > -1) {
11-
for (let j = match; j < match + words[i].length; j++) {
12-
boldMap[j] = 1
7+
const arr = new Array(S.length).fill(false)
8+
for(let w of words) {
9+
for(let i = 0, len = S.length - w.length; i <= len; i++) {
10+
const tmp = S.slice(i)
11+
if(tmp && tmp.startsWith(w)) {
12+
for(let j = i; j < i + w.length; j++) {
13+
arr[j] = true
14+
}
1315
}
1416
}
1517
}
1618
let res = ''
17-
let openTag = false
18-
for (let i = 0; i < S.length; i++) {
19-
if (boldMap[i] && !openTag) {
20-
res += `<b>`
21-
openTag = true
22-
} else if (!boldMap[i] && openTag) {
23-
res += `</b>`
24-
openTag = false
19+
for(let i = 0, len = S.length; i < len; i++) {
20+
if(arr[i] && (i === 0 || !arr[i - 1])) {
21+
res += '<b>'
2522
}
2623
res += S[i]
24+
if(arr[i] && (i === len - 1 || !arr[i + 1])) {
25+
res += '</b>'
26+
}
2727
}
28-
res += openTag ? `</b>` : ``
2928
return res
3029
}

0 commit comments

Comments
 (0)