原题连接在这里:https://leetcode.com/problems/add-bold-tag-in-string/description/html
题目:app
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.post
Example 1:ui
Input: s = "abcxyz123" dict = ["abc","123"] Output: "<b>abc</b>xyz<b>123</b>"
Example 2:url
Input: s = "aaabbcc" dict = ["aaa","aab","bc"] Output: "<b>aaabbc</b>c"
Note:spa
题解:code
相似Merge Intervals. 标记出dict中每一个word所在s的起始结束位置. sort后merge.htm
或者直接用boolean array来标记s的当前char是否出如今dict中word所在s的substring内.blog
Time Complexity: O(dict.length*s.length()*x). x是dict中word的平均长度.ip
Space: O(s.length()).
AC Java:
1 class Solution { 2 public String addBoldTag(String s, String[] dict) { 3 if(s == null || s.length() == 0 || dict == null || dict.length == 0){ 4 return s; 5 } 6 7 boolean [] mark = new boolean[s.length()]; 8 for(String word: dict){ 9 for(int i = 0; i<=s.length()-word.length(); i++){ 10 if(s.startsWith(word, i)){ 11 Arrays.fill(mark, i, i+word.length(), true); 12 } 13 } 14 } 15 16 int i = 0; 17 StringBuilder sb = new StringBuilder(); 18 while(i<mark.length){ 19 if(mark[i]){ 20 sb.append("<b>"); 21 while(i<mark.length && mark[i]){ 22 sb.append(s.charAt(i++)); 23 } 24 25 sb.append("</b>"); 26 }else{ 27 sb.append(s.charAt(i++)); 28 } 29 } 30 31 return sb.toString(); 32 } 33 }