最长公共子串和子序列的Python实现,带图示。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最长公共子串和子序列的Python实现,带图示。相关的知识,希望对你有一定的参考价值。
使用矩阵来记录两个子串之间各个字符之间的对应关系。
最长子串:矩阵中数字最大的就是最长子串的长度。若对应位置字符相同,则c[i][j] = c[i-1][j-1] + 1
1 def longSubStr(str1,str2): 2 len1 = len(str1) 3 len2 = len(str2) 4 longest,start1,start2 = 0,0,0 5 c = [[0 for i in range(len2+1)]for i in range(len1+1)] 6 for i in range(len1+1): 7 for j in range(len2+1): 8 if i == 0 or j == 0: 9 c[i][j] = 0 10 elif str1[i-1] == str2[j-1]: 11 c[i][j] = c[i-1][j-1]+1 12 else: 13 c[i][j] = 0 14 if (longest < c[i][j]): 15 longest = c[i][j] 16 start1 = i-longest 17 start2 = j-longest 18 19 return str1[start1:start1+longest],start1,start2
最长子序列:若对应位置字符相同,则c[i][j] = c[i-1][j-1] + 1,若不同,则max(c[i][j-1],c[i-1][j]).
1 def printLcs(flag,a,i,j): 2 if i==0 or j==0: 3 return 4 if flag[i][j]==‘OK‘: 5 printLcs(flag,a,i-1,j-1) 6 print a[i-1], 7 elif flag[i][j]==‘Left‘: 8 printLcs(flag,a,i,j-1) 9 else: 10 printLcs(flag,a,i-1,j) 11 12 def longSubSeq(str1,str2): 13 len1 = len(str1) 14 len2 = len(str2) 15 longest = 0 16 c = [[0 for i in range(len2+1)]for i in range(len1+1)] 17 flag = [[0 for i in range(len2+1)]for i in range(len1+1)] 18 for i in range(len1+1): 19 for j in range(len2+1): 20 if i == 0 or j == 0: 21 c[i][j] = 0 22 elif str1[i-1] == str2[j-1]: 23 c[i][j] = c[i-1][j-1]+1 24 flag[i][j] = ‘OK‘ 25 longest = max(longest,c[i][j]) 26 elif c[i][j-1] > c[i-1][j]: 27 c[i][j] =c[i][j-1] 28 flag[i][j] = ‘Left‘ 29 else: 30 c[i][j] =c[i-1][j] 31 flag[i][j] = ‘UP‘ 32 printLcs(flag,str1,len1,len2) 33 return longest 34 a=‘ABCBDAB‘ 35 b=‘BDCABA‘ 36 print longSubSeq(a,b)
以上是关于最长公共子串和子序列的Python实现,带图示。的主要内容,如果未能解决你的问题,请参考以下文章