Python程序如何将模式包含在粗体标签中?


假设我们有一段文本和一个称为模式的字符串列表,我们需要定义一个加粗函数,其中文本中与给定模式中的任何字符串匹配的所有子串都用 和 标签括起来。如果任何两个模式相邻或重叠,则应将其合并为一个标签。

因此,如果输入类似于text = "thisissampleline" patterns = ["this", "issam", "sample"],则输出将为"a<b>bc</b>d<b>ef</b>g",因为bc和ef与文本匹配并用<b>和</b>标签括起来。

为了解决这个问题,我们将遵循以下步骤

  • n := 文本大小

  • bold := 一个大小为n的列表,并填充False值

  • 对于范围为0到n的i,执行

    • 对于模式中的每个p,执行

      • 如果text[从索引i到结尾]的子串以p开头,则

        • 对于范围为0到p大小的j,执行

          • bold[i + j] := True

  • ans := 空字符串

  • 对于范围为0到n的i,执行

    • 如果bold[i]并且(i等于0或bold[i - 1]为false),则

      • ans := ans连接"<b>"

    • ans := ans + text[i]

    • 如果bold[i]并且(i等于n - 1或bold[i + 1]为false),则

      • ans := ans连接"</b>"

  • 返回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

更新于:2020年11月10日

304 次查看

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.