##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/616.html

# 616. Add Bold Tag in String (Medium)

Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, if two substrings wrapped by bold tags are consecutive, you need to combine them.

Example 1:

Input:
s = "abcxyz123"
dict = ["abc","123"]
Output:
"<b>abc</b>xyz<b>123</b>"


Example 2:

Input:
s = "aaabbcc"
dict = ["aaa","aab","bc"]
Output:
"<b>aaabbc</b>c"


Note:

1. The given dict won’t contain duplicates, and its length won’t exceed 100.
2. All the strings in input have length in range [1, 1000].

## Solution 1.

The first naive solution came to my mind is using a mask to denote which part of the string needs get bolded. So I created a vector<int> mask of length s.size(). For each word in dict, find its occurrence in s, mark the corresponding range to 1s in mask. Finally, output the result using that mask.

// OJ: https://leetcode.com/problems/add-bold-tag-in-string
// Time: O(DWK)
//    where D is size of dict, W is average length of words in dict
//    K is average occurrence of words in s.
// Space: O(N)
class Solution {
private:
void setMask(vector<int> &mask, int from, int to) {
for (int i = from; i < to; ++i) mask[i] = 1;
}
public:
string addBoldTag(string s, vector<string>& dict) {
for (string word : dict) {
int pos = s.find(word, 0);
while (pos != string::npos) {
pos = s.find(word, pos + 1);
}
}
string ans;
for (int i = 0; i < s.size(); ++i) {
if ((!i || mask[i - 1] == 0) && mask[i] == 1) ans += "<b>";
ans += s[i];
if (mask[i] == 1 && (mask[i + 1] == 0 || i == s.size() - 1)) ans += "</b>";
}
return ans;
}
};

• class Solution {
public String addBoldTag(String s, String[] dict) {
int length = s.length();
boolean[] bold = new boolean[length];
for (String str : dict) {
int strLength = str.length();
int beginIndex = 0;
while (beginIndex >= 0) {
beginIndex = s.indexOf(str, beginIndex);
if (beginIndex >= 0) {
for (int i = 0; i < strLength; i++)
bold[beginIndex + i] = true;
beginIndex++;
}
}
}
StringBuffer sb = new StringBuffer(s);
if (bold[length - 1])
sb.append("</b>");
for (int i = length - 1; i > 0; i--) {
if (bold[i] && !bold[i - 1])
sb.insert(i, "<b>");
else if (!bold[i] && bold[i - 1])
sb.insert(i, "</b>");
}
if (bold[0])
sb.insert(0, "<b>");
String boldStr = sb.toString();
return boldStr;
}
}

############

class Trie {
Trie[] children = new Trie[128];
boolean isEnd;

public void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
}

class Solution {
public String addBoldTag(String s, String[] words) {
Trie trie = new Trie();
for (String w : words) {
trie.insert(w);
}
List<int[]> pairs = new ArrayList<>();
int n = s.length();
for (int i = 0; i < n; ++i) {
Trie node = trie;
for (int j = i; j < n; ++j) {
int idx = s.charAt(j);
if (node.children[idx] == null) {
break;
}
node = node.children[idx];
if (node.isEnd) {
pairs.add(new int[] {i, j});
}
}
}
if (pairs.isEmpty()) {
return s;
}
List<int[]> t = new ArrayList<>();
int st = pairs.get(0)[0], ed = pairs.get(0)[1];
for (int j = 1; j < pairs.size(); ++j) {
int a = pairs.get(j)[0], b = pairs.get(j)[1];
if (ed + 1 < a) {
t.add(new int[] {st, ed});
st = a;
ed = b;
} else {
ed = Math.max(ed, b);
}
}
t.add(new int[] {st, ed});
int i = 0, j = 0;
StringBuilder ans = new StringBuilder();
while (i < n) {
if (j == t.size()) {
ans.append(s.substring(i));
break;
}
st = t.get(j)[0];
ed = t.get(j)[1];
if (i < st) {
ans.append(s.substring(i, st));
}
++j;
ans.append("<b>");
ans.append(s.substring(st, ed + 1));
ans.append("</b>");
i = ed + 1;
}
return ans.toString();
}
}

• // OJ: https://leetcode.com/problems/add-bold-tag-in-string
// Time: O(DWK)
//    where D is size of dict, W is average length of words in dict
//    K is average occurrence of words in s.
// Space: O(N)
class Solution {
public:
string addBoldTag(string s, vector<string>& A) {
int N = s.size();
vector<bool> bold(N);
for (auto &w : A) {
int i = s.find(w);
while (i != string::npos) {
for (int j = 0; j < w.size(); ++j) bold[i + j] = true;
i = s.find(w, i + 1);
}
}
string ans;
for (int i = 0; i < N; ) {
if (bold[i]) {
ans += "<b>";
while (i < N && bold[i]) ans += s[i++];
ans += "</b>";
} else ans += s[i++];
}
return ans;
}
};

• class Trie:
def __init__(self):
self.children = [None] * 128
self.is_end = False

def insert(self, word):
node = self
for c in word:
idx = ord(c)
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True

class Solution:
def addBoldTag(self, s: str, words: List[str]) -> str:
trie = Trie()
for w in words:
trie.insert(w)
n = len(s)
pairs = []
for i in range(n):
node = trie
for j in range(i, n):
idx = ord(s[j])
if node.children[idx] is None:
break
node = node.children[idx]
if node.is_end:
pairs.append([i, j])
if not pairs:
return s
st, ed = pairs[0]
t = []
for a, b in pairs[1:]:
if ed + 1 < a:
t.append([st, ed])
st, ed = a, b
else:
ed = max(ed, b)
t.append([st, ed])

ans = []
i = j = 0
while i < n:
if j == len(t):
ans.append(s[i:])
break
st, ed = t[j]
if i < st:
ans.append(s[i:st])
ans.append('<b>')
ans.append(s[st : ed + 1])
ans.append('</b>')
j += 1
i = ed + 1

return ''.join(ans)

############

class Solution(object):
def addBoldTag(self, s, dict):
"""
:type s: str
:type dict: List[str]
:rtype: str
"""
intervals = []
ans = []
for word in dict:
start = 0
loc = s.find(word, start)
while loc != -1:
intervals.append([loc, loc + len(word) - 1])
start = loc + 1
loc = s.find(word, start)

intervals = self.merge(intervals)
d = {}
for start, end in intervals:
d[start] = end
i = 0
while i < len(s):
if i in d:
ans.append("<b>{}</b>".format(s[i:d[i] + 1]))
i = d[i] + 1
else:
ans.append(s[i])
i += 1
return "".join(ans)

def merge(self, intervals):
ans = []
for intv in sorted(intervals, key=lambda x: x[0]):
if ans and ans[-1][1] + 1 >= intv[0]:
ans[-1][1] = max(ans[-1][1], intv[1])
else:
ans += intv,
return ans


• type Trie struct {
children [128]*Trie
isEnd    bool
}

func newTrie() *Trie {
return &Trie{}
}

func (this *Trie) insert(word string) {
node := this
for _, c := range word {
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}

func addBoldTag(s string, words []string) string {
trie := newTrie()
for _, w := range words {
trie.insert(w)
}
n := len(s)
var pairs [][]int
for i := range s {
node := trie
for j := i; j < n; j++ {
if node.children[s[j]] == nil {
break
}
node = node.children[s[j]]
if node.isEnd {
pairs = append(pairs, []int{i, j})
}
}
}
if len(pairs) == 0 {
return s
}
var t [][]int
st, ed := pairs[0][0], pairs[0][1]
for i := 1; i < len(pairs); i++ {
a, b := pairs[i][0], pairs[i][1]
if ed+1 < a {
t = append(t, []int{st, ed})
st, ed = a, b
} else {
ed = max(ed, b)
}
}
t = append(t, []int{st, ed})
var ans strings.Builder
i, j := 0, 0
for i < n {
if j == len(t) {
ans.WriteString(s[i:])
break
}
st, ed = t[j][0], t[j][1]
if i < st {
ans.WriteString(s[i:st])
}
ans.WriteString("<b>")
ans.WriteString(s[st : ed+1])
ans.WriteString("</b>")
i = ed + 1
j++
}
return ans.String()
}

func max(a, b int) int {
if a > b {
return a
}
return b
}