0616. Add Bold Tag in String
Description
**Input:** s = "abcxyz123", words = ["abc","123"]
**Output:** "<b>abc</b>xyz<b>123</b>"**Input:** s = "aaabbcc", words = ["aaa","aab","bc"]
**Output:** "<b>aaabbc</b>c"ac
Last updated
**Input:** s = "abcxyz123", words = ["abc","123"]
**Output:** "<b>abc</b>xyz<b>123</b>"**Input:** s = "aaabbcc", words = ["aaa","aab","bc"]
**Output:** "<b>aaabbc</b>c"Last updated
class Solution {
public String addBoldTag(String s, String[] dict) {
// edge cases
if (s == null || s.length() == 0 || dict == null || dict.length == 0) return s;
// which letter is covered?
boolean[] cover = new boolean[s.length()];
for (int i = 0; i < s.length(); i++) {
int len = 0;
for (String w : dict) {
if (s.startsWith(w, i)) {
len = Math.max(len, w.length());
}
}
Arrays.fill(cover, i, i+len, true);
}
// find those covered letters
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cover.length; i++) {
if (!cover[i]) {
sb.append(s.charAt(i));
} else {
int j = i;
while (j < cover.length && cover[j]) j++;
sb.append("<b>" + s.substring(i, j) + "</b>");
i = j-1;
}
}
// res
return sb.toString();
}
}
/*
boolean[] cover, determine word break.
iterate through index, find longest word, cover[i] = true
find all those cover[i] == true
*/