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標(biāo)志符包住他們的并集
- 如果連續(xù),也是一起包住。
首先有一種bruteforce的解法。 首先我們對(duì)字符串的每個(gè)位置對(duì)每個(gè)字典中的word進(jìn)行是否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處--。然后根據(jù)sum判斷interval是否結(jié)束。
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();
}
}