程序将模式包含在Python中的粗体标记中?
假设我们有一个文本和一个称为pattern的字符串列表,我们必须定义一个embolden函数,在该函数中,文本中与给定模式中的任何字符串匹配的所有子字符串都包装在 和 标记中。如果任何两个模式相邻或重叠,则应将它们合并到一个标签中。
因此,如果输入类似于text=“thisissampleline”pattern=[“this”,“issam”,“sample”],则输出将为“a<b>bc</b>d<b>ef</b>g”,因为bc和ef与文本匹配,并被包裹在<b>和</b>标记中。
为了解决这个问题,我们将按照以下步骤
n:=文字大小
粗体:=大小为n的列表,并用False值填充
对于0到n范围内的i,执行
如果text[从索引i到结束]的子字符串以p开头,则
粗体[i+j]:=真
对于范围0到p大小的j,执行
对于模式中的每个p
ans:=空字符串
对于0到n范围内的i,执行
ans:=ans串联“</b>”
ans:=ansconcatente“<b>”
如果bold[i]和(i与0相同或bold[i-1]为false),则
回答:=回答+文字[i]
如果bold[i]和(i与n-1相同或bold[i+1]为false),则
返回ans
让我们看一下下面的实现以获得更好的理解
示例
class Solution:
def solve(self, text, patterns):
n = len(text)
bold = [False] * n
for i in range(n):
for p in patterns:
if text[i:].startswith(p):
for j in range(len(p)):
bold[i + j] = True
ans = ""
for i in range(n):
if bold[i] and (i == 0 or not bold[i - 1]):
ans += ""
ans += text[i]
if bold[i] and (i == n - 1 or not bold[i + 1]):
ans += ""
return ans
ob = Solution()text = "thisissampleline"
patterns = ["this", "ssam", "sample"]
print(ob.solve(text, patterns))输入项
"thisissampleline", ["this", "ssam", "sample"]
输出结果
<b>this</b>i<b>ssample</b>line
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短