LeetCode 616. Add Bold Tag in String

原题链接在这里:https://leetcode.com/problems/add-bold-tag-in-string/description/

题目:

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:

  1. The given dict won't contain duplicates, and its length won't exceed 100.
  2. All the strings in input have length in range [1, 1000].

题解:

类似Merge Intervals. 标记出dict中每个word所在s的起始结束位置. sort后merge.

或者直接用boolean array来标记s的当前char是否出现在dict中word所在s的substring内.

Time Complexity: O(dict.length*s.length()*x). x是dict中word的平均长度.

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 }

 

posted @ 2017-10-20 02:07  Dylan_Java_NYC  阅读(766)  评论(0编辑  收藏  举报