[LintCode] Problem 1127 - 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.

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].

Example

No.1

Input:
s = “abcxyz123”
dict = [“abc”,”123”]

Output:
“<b>abc</b>xyz<b>123</b>“

No.2

Input:
s = “aaabbcc”
dict = [“aaa”,”aab”,”bc”]

Output:
“<b>aaabbc</b>c”

Code

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
public String addBoldTag(String s, String[] dict) {
StringBuilder sb = new StringBuilder();
int n = s.length();
int[] array = new int[n + 1];
int sum = 0;
int preSum = 0;

for (String word : dict) {
int idx = 0;

while ((idx = s.indexOf(word, idx)) >= 0) {
array[idx]++;
array[idx + word.length()]--;
idx++;
}
}

for (int i = 0; i <= n; i++) {
sum += array[i];

if (sum > 0 && preSum == 0)
sb.append("<b>");
else if (sum == 0 && preSum > 0)
sb.append("</b>");

if (i < n)
sb.append(s.charAt(i));

preSum = sum;
}

return sb.toString();
}