616. Add Bold Tag in String

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"

分析:
我们看当前字母开头有没有substring与dic里面的word 匹配。 如果有,至少说明那个字母应该是bold,如果不是,那个字母也有可能被包含在之前的substring里面。

https://www.youtube.com/watch?v=WXb3ItOlRfQ 

找出每个字符是否需要加bold,如果是,那么那个字符对应的value就是true, 然后把连在一起的true的字符放在bold里面就可以了

 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 }
posted @ 2021-03-12 11:26  北叶青藤  阅读(84)  评论(0)    收藏  举报