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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7697042.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值