Google
616 Add Bold Tag in String

1. Question

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:
1
Input:
2
s = "abcxyz123"
3
dict = ["abc","123"]
4
5
Output:
6
"<b>abc</b>xyz<b>123</b>"
Copied!
Example 2:
1
Input:
2
3
s = "aaabbcc"
4
dict = ["aaa","aab","bc"]
5
6
Output:
7
"<b>aaabbc</b>c"
Copied!
Note:
  1. 1.
    The given dict won't contain duplicates, and its length won't exceed 100.
  2. 2.
    All the strings in input have length in range [1, 1000].

2. Implementation

(1) Brute Force
1
class Solution {
2
public String addBoldTag(String s, String[] dict) {
3
if (dict == null || dict.length == 0) {
4
return s;
5
}
6
7
int n = s.length();
8
boolean[] addBold = new boolean[n];
9
10
for (int i = 0, end = 0; i < s.length(); i++) {
11
for (String word : dict) {
12
if (s.startsWith(word, i)) {
13
end = Math.max(i + word.length(), end);
14
}
15
}
16
addBold[i] = end > i;
17
}
18
19
StringBuilder res = new StringBuilder();
20
for (int i = 0; i < n; i++) {
21
if (!addBold[i]) {
22
res.append(s.charAt(i));
23
continue;
24
}
25
26
int j = i;
27
while (j < n && addBold[j]) j++;
28
res.append("<b>").append(s.substring(i, j)).append("</b>");
29
i = j - 1;
30
}
31
return res.toString();
32
}
33
}
Copied!
(2) Optimization
上一种做法是对于S的每个位置i,我们都尝试每个dict的word。其实我们只要将dict的word,通过indexOf找出word在s的位置index,然后将相应的区间在bold数组里mark成true即可
1
class Solution {
2
public String addBoldTag(String s, String[] dict) {
3
if (dict == null || dict.length == 0) {
4
return s;
5
}
6
7
int n = s.length();
8
boolean[] bold = new boolean[n];
9
10
for (int i = 0; i < dict.length; i++) {
11
int index = s.indexOf(dict[i]);
12
13
while (index != -1) {
14
for (int j = 0; j < dict[i].length(); j++) {
15
bold[index + j] = true;
16
}
17
18
index = s.indexOf(dict[i], index + 1);
19
}
20
}
21
22
StringBuilder res = new StringBuilder();
23
for (int i = 0; i < n; i++) {
24
if (!bold[i]) {
25
res.append(s.charAt(i));
26
continue;
27
}
28
int j = i;
29
while (j < n && bold[j]) ++j;
30
res.append("<b>").append(s.substring(i, j)).append("</b>");
31
i = j - 1;
32
}
33
return res.toString();
34
}
35
}
Copied!

3. Time & Space Complexity