美文网首页
616. Add Bold Tag in String

616. Add Bold Tag in String

作者: Nancyberry | 来源:发表于2018-05-30 02:33 被阅读0次

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

Solution

Boolean mark, O(m * n * L), S(m)

m: s.length()
n: dict.length
L: avg word length in dict

这道题跟"758. Bold Words in String"简直就是如出一辙。。没区别啊

都是用一个boolean[] isBold做标记,最后变成找连续为true的序列,在序列的头尾加上<b>和</b>标签。

class Solution {
    public String addBoldTag(String s, String[] dict) {
        int n = s.length();
        boolean[] isBold = new boolean[n];
        
        for (String t : dict) {
            for (int i = 0; i <= n - t.length(); ++i) {
                if (t.equals(s.substring(i, i + t.length()))) {
                    for (int j = i; j < i + t.length(); ++j) {
                        isBold[j] = true;
                    }
                }
            }
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; ++i) {
            if (isBold[i] && (i == 0 || !isBold[i - 1])) {
                sb.append("<b>");
            }
            
            sb.append(s.charAt(i));
            
            if (isBold[i] && (i == n - 1 || !isBold[i + 1])) {
                sb.append("</b>");
            }
        }
        
        return sb.toString();
    }
}

相关文章

网友评论

      本文标题:616. Add Bold Tag in String

      本文链接:https://www.haomeiwen.com/subject/gjwzjftx.html