Add Bold Tag in String Problem
Description
LeetCode Problem 616.
You are given a string s and an array of strings words.
You should add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in words.
- If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag.
- If two substrings wrapped by bold tags are consecutive, you should combine them.
Return s after adding the bold tags.
Example 1:
Input: s = "abcxyz123", words = ["abc","123"]
Output: "<b>abc</b>xyz<b>123</b>"
Explanation: The two strings of words are substrings of s as following: "abcxyz123".
We add <b> before each substring and </b> after each substring.
Example 2:
Input: s = "aaabbb", words = ["aa","b"]
Output: "<b>aaabbb</b>"
Explanation:
"aa" appears as a substring two times: "aaabbb" and "aaabbb".
"b" appears as a substring three times: "aaabbb", "aaabbb", and "aaabbb".
We add <b> before each substring and </b> after each substring: "<b>a<b>a</b>a</b><b>b</b><b>b</b><b>b</b>".
Since the first two <b>'s overlap, we merge them: "<b>aaa</b><b>b</b><b>b</b><b>b</b>".
Since now the four <b>'s are consecutive, we merge them: "<b>aaabbb</b>".
Constraints:
1 <= s.length <= 10000 <= words.length <= 1001 <= words[i].length <= 1000sandwords[i]consist of English letters and digits.- All the values of
wordsare unique.
Note: This question is the same as 758. Bold Words in String.
Solution
Approach: Trie + Mark Bold Characters
The merging rules (overlapping or touching matches get one tag) are much easier to handle per character than per interval: a character is bold if any occurrence of any word covers it, and the tags simply go around every maximal run of bold characters. Two matches that overlap or touch form one unbroken run, so they automatically get a single pair of tags.
To find the matches, put all words into a trie. Then, for every start position i in s, walk the trie along s[i], s[i+1], ... until there is no child for the next character. Each node we pass that ends a word gives a match s[i..j]. We only care about the longest one, so remember the furthest end seen so far in a variable end. Since a match that starts at or before i and ends after i marks i as bold, character i is bold exactly when i < end after processing start i.
Finally build the answer: open <b> before a bold character whose left neighbor is not bold, and close </b> after a bold character whose right neighbor is not bold.
Two details: from a start position, keep walking past the first word that ends there, since a longer word may match too ("a" and "abc" in "abc"). And words may be empty or contain words longer than s; both just produce no matches, and s comes back unchanged. In example 2, the two "aa" matches cover indices 0 to 2 and the "b" matches cover 3 to 5, so all six characters are bold and get a single pair of tags.
Complexity: Building the trie takes O(total length of words). Walking from each of the n start positions is at most O(n) steps, so O(n2) time in the worst case. O(total length of words + n) extra space.
class Trie:
def __init__(self):
self.children = {}
self.is_end = False
class Solution:
def addBoldTag(self, s: str, words: List[str]) -> str:
root = Trie()
for w in words:
node = root
for c in w:
node = node.children.setdefault(c, Trie())
node.is_end = True
n = len(s)
bold = [False] * n
end = 0 # every position before end is covered by some word
for i in range(n):
# Walk the trie from i to find the longest word starting here.
node = root
for j in range(i, n):
node = node.children.get(s[j])
if node is None:
break
if node.is_end:
end = max(end, j + 1)
bold[i] = i < end
# Wrap every maximal run of bold characters.
out = []
for i, c in enumerate(s):
if bold[i] and (i == 0 or not bold[i - 1]):
out.append("<b>")
out.append(c)
if bold[i] and (i == n - 1 or not bold[i + 1]):
out.append("</b>")
return "".join(out)