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"
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].
一刷
题解:
- 如果有overlap, 用bold标志符包住他们的并集
- 如果连续,也是一起包住。
首先有一种bruteforce的解法。 首先我们对字符串的每个位置对每个字典中的word进行是否startwith的判断。
class Solution {
public String addBoldTag(String s, String[] dict) {
boolean[] bold = new boolean[s.length()];
for (int i = 0, end = 0; i < s.length(); i++) {
for (String word : dict) {
if (s.startsWith(word, i)) {
end = Math.max(end, i + word.length());
}
}
//judge whether this index is bold
bold[i] = end>i;
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++){
if(!bold[i]){
sb.append(s.charAt(i));
continue;
}
int j=i;
while(j<s.length() && bold[j]) j++;
sb.append("<b>").append(s.substring(i,j)).append("</b>");
i = j-1;
}
return sb.toString();
}
}
Speed up
用indexof找出interval
然后用interval求并集的方式,比如[1,2,3]那么在1处++, 在4处--。然后根据sum判断interval是否结束。
class Solution {
public String addBoldTag(String s, String[] dict) {
if(dict.length == 0 || s==null || s.length() == 0) return s;
int n = s.length();
int[] mark = new int[n+1];
for(String word:dict){
int i=-1;
while((i=s.indexOf(word, i+1))>=0){
mark[i]++;
mark[i+word.length()]--;
}
}
int prev = 0;
StringBuilder sb = new StringBuilder();
for(int i=0; i<=n; i++){
int cur = prev + mark[i];
if(prev == 0 && cur>0) sb.append("<b>");
if(prev>0 && cur==0) sb.append("</b>");
if(i==n) break;
sb.append(s.charAt(i));
prev = cur;
}
return sb.toString();
}
}