LeetCode 616. Add Bold Tag in String

原題連接在這裏: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

  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].

題解: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 }
相關文章
相關標籤/搜索