问题描述:
最长公共子串和最长公共子序列问题很相似,但是最长公共子串要求不可以间断,必须是连续的,一旦不相等便记录为0,相等便让子串长度加1,依次遍历。
动态规划
import numpy
def Longest_Common_Substring(X, Y):
"""
:param X: 字符串X
:param Y: 字符串Y
:return: X和Y的最长公共子串
"""
# 初始化
n = len(X)
m = len(Y)
l_max = 0 # 子串长度
p_max = 0 # 终止位置
# 新建二维数组C[0...n,0...m]
C = [[0 for i in range(m + 1)] for j in range(n + 1)]
# 动态规划
# 依次计算子问题
for i in range(0, n):
for j in range(0, m):
if X[i] != Y[j]: # 末尾不等
C[i + 1][j + 1] = 0
# 末尾相等
else:
C[i + 1][j + 1] = C[i][j] + 1
# 记录最长公共子串
if C[i + 1][j + 1] > l_max:
l_max = C[i + 1][j + 1]
p_max = i
# 最优追踪方案
def Print_LCS(X, l_max, p_max):
"""
:param X: 字符串X
:param l_max: 最长公共子串长度
:param p_max: 终止位置
:return:
"""
# 无公共子串
if l_max < 0:
return None
print("最长公共子串:", end="")
# 追踪最优解
for i in range(p_max - l_max + 1, p_max + 1):
print(X[i], end=",")
return f"{Print_LCS(X, l_max, p_max)}\n最长公共子串记录表:\n{numpy.asmatrix(C)}\n最长公共子串长度:{l_max}\n起始位置:{p_max-l_max+1}, 终止位置:{p_max}"
if __name__ == '__main__':
X = ["A", "B", "C", "A", "D", "B", "B"]
Y = ["B", "C", "E", "D", "B", "B"]
print(Longest_Common_Substring(X, Y))