Skip to content

Commit 5d874b5

Browse files
committed
Add solution #616
1 parent 7f1e2dd commit 5d874b5

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,7 @@
576576
606|[Construct String from Binary Tree](./solutions/0606-construct-string-from-binary-tree.js)|Easy|
577577
609|[Find Duplicate File in System](./solutions/0609-find-duplicate-file-in-system.js)|Medium|
578578
611|[Valid Triangle Number](./solutions/0611-valid-triangle-number.js)|Medium|
579+
616|[Add Bold Tag in String](./solutions/0616-add-bold-tag-in-string.js)|Medium|
579580
617|[Merge Two Binary Trees](./solutions/0617-merge-two-binary-trees.js)|Easy|
580581
621|[Task Scheduler](./solutions/0621-task-scheduler.js)|Medium|
581582
622|[Design Circular Queue](./solutions/0622-design-circular-queue.js)|Medium|
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* 616. Add Bold Tag in String
3+
* https://leetcode.com/problems/add-bold-tag-in-string/
4+
* Difficulty: Medium
5+
*
6+
* You are given a string s and an array of strings words.
7+
*
8+
* You should add a closed pair of bold tag <b> and </b> to wrap the substrings in s that
9+
* exist in words.
10+
* - If two such substrings overlap, you should wrap them together with only one pair of
11+
* closed bold-tag.
12+
* - If two substrings wrapped by bold tags are consecutive, you should combine them.
13+
*
14+
* Return s after adding the bold tags.
15+
*/
16+
17+
/**
18+
* @param {string} s
19+
* @param {string[]} words
20+
* @return {string}
21+
*/
22+
var addBoldTag = function(s, words) {
23+
const boldIntervals = [];
24+
25+
for (const word of words) {
26+
let start = s.indexOf(word);
27+
while (start !== -1) {
28+
boldIntervals.push([start, start + word.length]);
29+
start = s.indexOf(word, start + 1);
30+
}
31+
}
32+
33+
if (!boldIntervals.length) return s;
34+
35+
boldIntervals.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
36+
37+
const mergedIntervals = [];
38+
let [currentStart, currentEnd] = boldIntervals[0];
39+
40+
for (let i = 1; i < boldIntervals.length; i++) {
41+
const [nextStart, nextEnd] = boldIntervals[i];
42+
if (nextStart <= currentEnd) {
43+
currentEnd = Math.max(currentEnd, nextEnd);
44+
} else {
45+
mergedIntervals.push([currentStart, currentEnd]);
46+
[currentStart, currentEnd] = [nextStart, nextEnd];
47+
}
48+
}
49+
mergedIntervals.push([currentStart, currentEnd]);
50+
51+
let result = '';
52+
let lastEnd = 0;
53+
for (const [start, end] of mergedIntervals) {
54+
result += s.slice(lastEnd, start) + '<b>' + s.slice(start, end) + '</b>';
55+
lastEnd = end;
56+
}
57+
58+
result += s.slice(lastEnd);
59+
60+
return result;
61+
};

0 commit comments

Comments
 (0)