与 最长公共子序列类似
只是最长公共子串必须连续 所以只能走斜线!!!!
1 ''' 2 LCS 最长公共子序列 3 ''' 4 5 6 def LCS_len(x, y): 7 m = len(x) 8 n = len(y) 9 dp = [[0] * (n + 1) for i in range(m + 1)] 10 B = [[' '] * (n + 1) for i in range(m + 1)] 11 for i in range(1, m + 1): 12 for j in range(1, n + 1): 13 if x[i - 1] == y[j - 1]: 14 dp[i][j] = dp[i - 1][j - 1] + 1 15 B[i][j] = 'X' 16 17 18 return dp, B 19 20 21 def LCS_str(B, x, i, j): 22 if i == 0 or j == 0: 23 return 24 if B[i][j] == 'X': 25 print(x[i - 1]) 26 LCS_str(B, x, i - 1, j - 1) 27 28 # elif B[i][j] == 'L': 29 # LCS_str(B, x, i - 1, j) 30 else: 31 32 LCS_str(B, x, i, j - 1) 33 34 35 36 def main(): 37 x = 'bab' 38 y = 'caba' 39 dp, B = LCS_len(x, y) 40 LCS_str(B, x, len(x), len(y)) 41 main()