在 Python 中如何将模式括入粗体标签?\

pythonserver side programmingprogramming更新于 2026/2/16 16:44:17

假设我们有一个文本和一个称为模式的字符串列表,我们必须定义一个 embolden 函数,其中文本中与给定模式中的任何字符串匹配的所有子字符串都包裹在  and  标签中。如果任何两个模式相邻或重叠,则应将它们合并为一个标签。

因此,如果输入类似于 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,执行

      • 如果文本的子字符串[从索引 i 到末尾]以 p 开头,则

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

          • bold[i + j] :=真

  • ans := 空字符串

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

    • 如果 bold[i] 并且 (i 与 0 相同或 bold[i - 1] 为假),则

      • ans := ans 连接 <b>"

    • ans := ans + text[i]

    • 如果 bold[i] 并且 (i 与 n - 1 相同或 bold[i + 1] 为假),则

      • 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

相关文章


有用资源