|
| 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