Add Bold Tag in String
String, Sweep Line, Interval
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>"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)
merge the list of intervals (see https://leetcode.com/problems/merge-intervals/)
go through the merged interval list and insert the tags into the string
Java String indexOf()
IIRC Java's implementation of .indexOf() is just the naive string matching algorithm, which is O(n+m) average and O(n*m) worst case.
12 ms, faster than 80.46%
Trie for String Search
https://leetcode.com/problems/add-bold-tag-in-string/discuss/104250/Java-Trie-Solution
33 ms, faster than 32.72%
Last updated
Was this helpful?