Bold Words in String Problem
Description
LeetCode Problem 758.
Given an array of keywords words and a string s, make all appearances of all keywords words[i] in s bold. Any letters between <b> and </b> tags become bold.
Return s after adding the bold tags. The returned string should use the least number of tags possible, and the tags should form a valid combination.
Example 1:
Input: words = ["ab","bc"], s = "aabcd"
Output: "a<b>abc</b>d"
Explanation: Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it is incorrect.
Example 2:
Input: words = ["ab","cb"], s = "aabcd"
Output: "a<b>ab</b>cd"
Constraints:
1 <= s.length <= 5000 <= words.length <= 501 <= words[i].length <= 10sandwords[i]consist of lowercase English letters.
Note: This question is the same as 616. Add Bold Tag in String.
Solution
Approach: Mark Bold Characters
Tags are hard to merge directly, but characters are easy: a character is bold if any keyword occurrence covers it. Once we know which characters are bold, the answer wraps every maximal run of bold characters in a single pair of tags. Overlapping matches (example 1) and matches that only touch (like "ab" and "cd" in "abcd") both form one unbroken run, so they get one pair of tags, which is the fewest possible.
To mark the characters, scan the start positions i from left to right and keep end, the first index not covered by any match that started at or before i. At each i, check every keyword w: if s starts with w at position i, set end = max(end, i + len(w)). Then character i is bold exactly when i < end. Using the furthest end means we never need to store the matches themselves.
Then build the string: put <b> before a bold character whose left neighbor is not bold, and </b> after a bold character whose right neighbor is not bold.
Edge cases: words may be empty, or no keyword may occur in s; then no character is bold and s comes back unchanged. Repeated or overlapping occurrences of the same keyword ("aa" in "aaaaa") are all found, because we test every start position.
Complexity: O(n · W · L) time, where n = len(s), W is the number of keywords and L their maximum length (at most 500 · 50 · 10 checks). O(n) extra space.
class Solution:
def boldWords(self, words: List[str], s: str) -> str:
n = len(s)
bold = [False] * n
end = 0 # first index not covered by any keyword that starts at or before i
for i in range(n):
for w in words:
if s.startswith(w, i):
end = max(end, i + len(w))
bold[i] = i < end
ans = []
for i, c in enumerate(s):
if bold[i] and (i == 0 or not bold[i - 1]):
ans.append("<b>")
ans.append(c)
if bold[i] and (i == n - 1 or not bold[i + 1]):
ans.append("</b>")
return "".join(ans)