如何在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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP