如何在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.