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"
分析:
方法一:
对于字典里的每一个词,找出每个词出现在s里面的位置,我们用interval来表示。最后我们把这些interval merge一下,就是所有需要bold的点。
1 public class Solution { 2 3 public String addBoldTag(String s, String[] dict) { 4 List<Interval> list = new ArrayList<>(); 5 for (String str : dict) { 6 int index = s.indexOf(str); 7 while (index != -1) { 8 list.add(new Interval(index, index + str.length())); 9 index = s.indexOf(str, index + 1); 10 } 11 } 12 Collections.sort(list, (a, b) -> a.start - b.start); 13 14 List<Interval> res = mergeInterval(list); 15 16 int pre = 0; 17 StringBuilder sb = new StringBuilder(); 18 for (Interval ele : res) { 19 sb.append(s.substring(pre, ele.start)); 20 sb.append("<b>" + s.substring(ele.start, ele.end) + "</b>"); 21 pre = ele.end; 22 } 23 24 if (pre < s.length()) { 25 sb.append(s.substring(pre)); 26 } 27 28 return sb.toString(); 29 } 30 31 public List<Interval> mergeInterval(List<Interval> list) { 32 List<Interval> res = new ArrayList<>(); 33 if (list == null || list.size() == 0) { 34 return res; 35 } 36 37 res.add(list.get(0)); 38 for (int i = 1; i < list.size(); i++) { 39 Interval temp = list.get(i); 40 Interval last = res.get(res.size() - 1); 41 if (!overlap(temp, last)) { 42 res.add(temp); 43 } else { 44 last.end = Math.max(temp.end, last.end); 45 last.start = Math.min(temp.start, last.start); 46 } 47 } 48 return res; 49 } 50 51 private boolean overlap(Interval i1, Interval i2) { 52 return Math.max(i1.start, i2.start) <= Math.min(i1.end, i2.end); 53 } 54 } 55 56 class Interval { 57 int start; 58 int end; 59 60 public Interval(int start, int end) { 61 this.start = start; 62 this.end = end; 63 } 64 }
方法二:
我们看当前字母开头有没有substring与dic里面的word 匹配。 如果有,至少说明那个字母应该是bold,如果不是,那个字母也有可能被包含在之前的substring里面。
1 public class Solution { 2 public String addBoldTag(String s, String[] dict) { 3 boolean[] bold = new boolean[s.length()]; 4 for (int i = 0, end = 0; i < s.length(); i++) { 5 for (String word : dict) { 6 if (s.startsWith(word, i)) { 7 end = Math.max(end, i + word.length()); 8 } 9 } 10 bold[i] = end > i; 11 } 12 13 StringBuilder result = new StringBuilder(); 14 for (int i = 0; i < s.length(); i++) { 15 if (!bold[i]) { 16 result.append(s.charAt(i)); 17 continue; 18 } 19 int j = i; 20 while (j < s.length() && bold[j]) j++; 21 result.append("<b>" + s.substring(i, j) + "</b>"); 22 i = j - 1; 23 } 24 25 return result.toString(); 26 } 27 }