Add Bold Tag in String && Bold Words in String

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"

Constraints:

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

Note: This question is the same as 758: Loading...

思路:每个position,用startswith,判断每个word是否以这个为起点,把S转换成[0,1111 000] 1代表bold,0代表不是bold,然后用stringbuilder 加起来, T(O(len(s) * L^2);

[11...]头部 [000 1111] 这两种情况需要加<b>

[...11] 尾部 [1111000] 这两种情况需要加</b>

class Solution {
    public String addBoldTag(String s, String[] words) {
        int n = s.length();
        int[] bold = new int[n];
        int end = 0;
        // 将需要bold的string,用1111来标识;
        for(int i = 0; i < s.length(); i++) {
            for(String word: words) {
                if(s.startsWith(word, i)) {
                    end = Math.max(end, i + word.length());
                }
            }
            bold[i] = end > i ? 1 : 0;
        }
        
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < n; i++) {
            if(bold[i] == 1 && (i == 0 || (i >= 1 && bold[i - 1] == 0))) {
                sb.append("<b>");
            }
            sb.append(s.charAt(i));
            if(bold[i] == 1 && (i == n - 1 || (i < n - 1 && bold[i + 1] == 0))) {
                sb.append("</b>");
            }
        }
        return sb.toString();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值