Skip to content

Commit 3b7bfb2

Browse files
committed
Add solution #758
1 parent 5d874b5 commit 3b7bfb2

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -687,6 +687,7 @@
687687
754|[Reach a Number](./solutions/0754-reach-a-number.js)|Medium|
688688
756|[Pyramid Transition Matrix](./solutions/0756-pyramid-transition-matrix.js)|Medium|
689689
757|[Set Intersection Size At Least Two](./solutions/0757-set-intersection-size-at-least-two.js)|Hard|
690+
758|[Bold Words in String](./solutions/0758-bold-words-in-string.js)|Medium|
690691
761|[Special Binary String](./solutions/0761-special-binary-string.js)|Hard|
691692
762|[Prime Number of Set Bits in Binary Representation](./solutions/0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
692693
763|[Partition Labels](./solutions/0763-partition-labels.js)|Medium|
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* 758. Bold Words in String
3+
* https://leetcode.com/problems/bold-words-in-string/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of keywords words and a string s, make all appearances of all keywords words[i]
7+
* in s bold. Any letters between <b> and </b> tags become bold.
8+
*
9+
* Return s after adding the bold tags. The returned string should use the least number of tags
10+
* possible, and the tags should form a valid combination.
11+
*/
12+
13+
/**
14+
* @param {string[]} words
15+
* @param {string} s
16+
* @return {string}
17+
*/
18+
var boldWords = function(words, s) {
19+
const boldIntervals = [];
20+
21+
for (const word of words) {
22+
let start = s.indexOf(word);
23+
while (start !== -1) {
24+
boldIntervals.push([start, start + word.length]);
25+
start = s.indexOf(word, start + 1);
26+
}
27+
}
28+
29+
if (!boldIntervals.length) return s;
30+
31+
boldIntervals.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
32+
33+
const mergedIntervals = [];
34+
let [currentStart, currentEnd] = boldIntervals[0];
35+
36+
for (let i = 1; i < boldIntervals.length; i++) {
37+
const [nextStart, nextEnd] = boldIntervals[i];
38+
if (nextStart <= currentEnd) {
39+
currentEnd = Math.max(currentEnd, nextEnd);
40+
} else {
41+
mergedIntervals.push([currentStart, currentEnd]);
42+
[currentStart, currentEnd] = [nextStart, nextEnd];
43+
}
44+
}
45+
mergedIntervals.push([currentStart, currentEnd]);
46+
47+
let result = '';
48+
let lastEnd = 0;
49+
for (const [start, end] of mergedIntervals) {
50+
result += s.slice(lastEnd, start) + '<b>' + s.slice(start, end) + '</b>';
51+
lastEnd = end;
52+
}
53+
54+
result += s.slice(lastEnd);
55+
56+
return result;
57+
};

0 commit comments

Comments
 (0)