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.