758. Bold Words in String

Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold.

The returned string should use the least number of tags possible, and of course the tags should form a valid combination.

For example, given that words = ["ab", "bc"] and S = "aabcd", we should return "a<b>abc</b>d". Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it is incorrect.

Note:

  1. words has length in range [0, 50].
  2. words[i] has length in range [1, 10].
  3. S has length in range [0, 500].
  4. All characters in words[i] and S are lowercase letters.

思路:先求出必须以i位置的字符开头的,最多可以扩充到的距离,然后后stack合并有相交的interval

直接开个数组存放要不要bold,估计也行

class Solution:
    def boldWords(self, words, S):
        """
        :type words: List[str]
        :type S: str
        :rtype: str
        """
        intervals = []
        words = set(words)
        for i in range(len(S)):
            j = len(S)
            while j>i and S[i:j] not in words: j-=1
            if j>i: intervals.append([i, j-1])
            
        ret = []
        for interval in intervals:
            if not ret: ret.append(interval)
            else:
                t = ret.pop()
                if t[1]>=interval[0]-1:
                    ret.append([t[0], max(t[1], interval[1])])
                else:
                    ret.append(t)
                    ret.append(interval)
                    
        res,i,p = '',0,0
        while p<len(S):
            if i<len(ret) and p==ret[i][0]:
                res += '<b>'+S[ret[i][0]:ret[i][1]+1]+'</b>'
                p = ret[i][1]+1
                i += 1
            else:
                res += S[p]
                p += 1
        return res
s=Solution()
print(s.boldWords(words = ["ab", "bc"], S = "aabcd"))
            
                



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值