Python - 長度為 K 的子字串匹配位置數


在給定的問題陳述中,我們必須使用 Python 程式設計找到長度為 K 的子字串匹配的位置數。因此,此問題有助於從輸入字串中獲取所有長度為 K 的子字串。

理解問題

手頭的問題需要一個包含一些子字串的輸入字串。因此,我們必須顯示給定字串中子字串匹配的位置數。例如,讓我們看看下面的圖片 -

在上圖中,我們可以看到 K 的值為“aaab”,因此在計算此字串後,輸出將為 4,因為該字串在輸入字串中出現了四次。

上述問題的邏輯

為了解決這個問題,我們將定義子字串和子字串長度 K。然後,我們將從給定字串中提取子字串,並與定義的字串進行匹配,如果兩者匹配,則將計數值加 1。最後,返回計數值以顯示長度為 K 的子字串匹配的位置數。

演算法

  • 步驟 1 - 首先初始化輸入字串、K 值和子字串的變數,如 input_str、K 和 substr。

  • 步驟 2 - 定義一個函式來計算輸入字串中子字串的匹配位置。並在該函式內部傳遞三個引數,如 input_str、K 和 substr。

  • 步驟 3 - 然後初始化一個名為 counter 的變數來記錄子字串的計數。

  • 步驟 4 - 將在字串索引上啟動一個迴圈,直到字串長度 - K + 1。這將表示子字串的大小。

  • 步驟 5 - 在迴圈內部,我們將從字串中提取 K。

  • 步驟 6 - 接下來,將提取的字串與給定的子字串進行比較。如果兩者相同,我們將使計數器值加 1。

  • 步驟 7 - 迭代完整個字串後,我們將返回最終的計數器值以在控制檯上顯示。

示例

# Initialize the input string
input_str = "aaabddhaaabnsnsaaabkskd"
K = 4
# Initialize the substring
substr = "aaab"
# Define the function to count the matching string
def count_positions(input_str, K, substr):
   # Initialize the counter with 0
   counter = 0
   # Iterate the input string
   for i in range(len(input_str) - K + 1):
      str_size = input_str[i:i+K]
      if str_size == substr:
         counter += 1
   return counter
# Call the above function
Output = count_positions(input_str, K, substr)
print(f"The substring '{substr}' with length {K} is matching at: '{Output}' positions")

輸出

The substring 'aaab' with length 4 is matching at: '3' positions

複雜度

查詢長度為 K 的子字串匹配位置數的時間複雜度為 O(N),其中 N 是給定 input_str 的長度。因為程式碼迭代字串從 0 到 len(input_str) - K +1。

結論

由於我們已成功使用 Python 解決了給定的問題。我們使用了基本的 Python 功能來獲得有效的解決方案,以獲取子字串的位置數。

更新於: 2023年10月17日

114 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.