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