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>"
Example 2:
Input: s = "aaabbcc" dict = ["aaa","aab","bc"] Output: "<b>aaabbc</b>c"
Constraints:
- 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].
Note: This question is the same as 758: Loading...
思路:每个position,用startswith,判断每个word是否以这个为起点,把S转换成[0,1111 000] 1代表bold,0代表不是bold,然后用stringbuilder 加起来, T(O(len(s) * L^2);
[11...]头部 [000 1111] 这两种情况需要加<b>
[...11] 尾部 [1111000] 这两种情况需要加</b>
class Solution {
public String addBoldTag(String s, String[] words) {
int n = s.length();
int[] bold = new int[n];
int end = 0;
// 将需要bold的string,用1111来标识;
for(int i = 0; i < s.length(); i++) {
for(String word: words) {
if(s.startsWith(word, i)) {
end = Math.max(end, i + word.length());
}
}
bold[i] = end > i ? 1 : 0;
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++) {
if(bold[i] == 1 && (i == 0 || (i >= 1 && bold[i - 1] == 0))) {
sb.append("<b>");
}
sb.append(s.charAt(i));
if(bold[i] == 1 && (i == n - 1 || (i < n - 1 && bold[i + 1] == 0))) {
sb.append("</b>");
}
}
return sb.toString();
}
}