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