如何在Python中查詢多個字串的最長公共子串?


在本文中,我們將學習如何在Python中查詢多個字串的最長公共子串。

查詢**最長公共子串**的唯一方法是使用最長公共子串演算法。我們將定義一個接受兩個字串的函式,然後迭代這兩個字串,查詢公共子序列並計算長度。

我們將透過迭代並計算子序列的長度來檢查整個字串,並將返回最長的公共子序列。如果兩個給定字串之間沒有任何公共子序列,我們將得到一個空字串作為輸出。

示例

在下面的示例中,我們以兩個字串作為輸入,並展示了最長公共子序列演算法的實現以及如何找到最長公共子序列。

def longest_common_substring(str1, sub):
   m = [[0] * (1 + len(sub)) for i in range(1 + len(str1))]
   longest, x_longest = 0, 0
   for x in range(1, 1 + len(str1)):
      for y in range(1, 1 + len(sub)):
         if str1[x - 1] == sub[y - 1]:
            m[x][y] = m[x - 1][y - 1] + 1
            if m[x][y] > longest:
               longest = m[x][y]
               x_longest = x
            else:
               m[x][y] = 0
   return str1[x_longest - longest: x_longest]
   
str1 = "Welcome to Tutorialspoint"
print("The given string is ")
print(str1)

sub1 = "Tutorial"
print("The first sub-string is")
print(sub1)
print("The longest common subsequence between'",str1,"'and '",sub1,"' is")
print(longest_common_substring(str1, sub1))

sub2 = "12345"
print("The second sub-string is")
print(sub2)
print("The longest common subsequence between'",str1,"'and '",sub2,"' is")
print(longest_common_substring(str1, sub2))

輸出

以下是上述程式碼的輸出:

The given string is
Welcome to Tutorialspoint
The first sub-string is
Tutorial
The longest common subsequence between' Welcome to Tutorialspoint 'and ' Tutorial ' is Tutorial
1
The second sub-string is
12345
The longest common subsequence between' Welcome to Tutorialspoint 'and ' 12345 ' is

更新於:2022年12月7日

2K+ 閱讀量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.