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>"Input:
s = "aaabbcc"
dict = ["aaa","aab","bc"]
Output:
"<b>aaabbc</b>c"
Example 2:
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].
Solution & Analysis
Merge Interval + Sweep Line
先找到所匹配的dict中的词对应的intervals,再合并intervals,最后插入bold tag
Another way to think about this:
create a list of tuples/intervals with opening/closing positions, e.g. (open_index, close_index)
class Solution {
String prefix = "<b>";
String suffix = "</b>";
public String addBoldTag(String s, String[] dict) {
if (s == null) {
return "";
}
int end = -1;
StringBuilder sb = new StringBuilder();
Trie trie = new Trie();
for (String word : dict) trie.insert(word);
for (int i = 0; i < s.length(); i++) {
if (end >= i) {
end = Math.max(end, trie.search(s, i));
} else {
end = trie.search(s, i);
if (end > i) {
sb.append(prefix);
}
}
if (end == i) sb.append(suffix);
sb.append(s.charAt(i));
}
if (end == s.length()) sb.append(suffix);
return sb.toString();
}
public static class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
if (word == null) return;
TrieNode node = root;
for (char c : word.toCharArray()) {
if (!node.map.containsKey(c)) {
node.map.put(c, new TrieNode());
}
node = node.map.get(c);
}
node.end = true;
}
public int search(String s, int index) {
TrieNode node = root;
int res = -1;
while (node != null && index < s.length()) {
node = node.map.getOrDefault(s.charAt(index++), null);
if (node != null && node.end == true) {
res = index;
}
}
return res;
}
}
public static class TrieNode {
Map<Character, TrieNode> map;
boolean end;
public TrieNode() {
map = new HashMap<>();
end = false;
}
}
}