616. Add Bold Tag in String

Given a string s and a list of strings dict, you need to add a closed pair of bold tag and 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
2
3
4
5
Input:
s = "abcxyz123"
dict = ["abc","123"]
Output:
"<b>abc</b>xyz<b>123</b>"

Example 2:

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

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

解法1:

这题可以分成两个部分,第一个部分是找出来所有在字典中出现的词。
这一步可以遍历字典,按照每一个词的长度来遍历原字符串来找出出现的位置。可以用一个array来存储每一个词出现的(start, end)。
然后问题就变成,要把这些pair先merge一下,然后头尾加上tag即可。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
public String addBoldTag(String s, String[] dict) {
List<int[]> pairs = new ArrayList<int[]>();
for (String d : dict) {
int len = d.length();
for (int i = 0; i <= s.length() - len; i++) {
if (d.equals(s.substring(i, i + len))) {
pairs.add(new int[] {i,i + len - 1});
}
}
}
Collections.sort(pairs, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
StringBuilder builder = new StringBuilder();
int prev = 0;
for (int i = 0; i < pairs.size(); i++) {
builder.append(s.substring(prev, pairs.get(i)[0]));
// Merge intervals
int start = pairs.get(i)[0];
int end = pairs.get(i)[1];
while (i < pairs.size() - 1 && pairs.get(i + 1)[0] <= end + 1) {
end = Math.max(end, pairs.get(i + 1)[1]);
i++;
}
builder.append("<b>" + s.substring(start, end + 1) + "</b>");
prev = end + 1;
}
builder.append(s.substring(prev, s.length()));
return builder.toString();
}
}