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:
words
has length in range[0, 50]
.words[i]
has length in range[1, 10]
.S
has length in range[0, 500]
.- All characters in
words[i]
andS
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"))