1.问题
LCS算法和背包算法,特别要求举例时采用不同于讲义的数据进行推导
2.解析
对于字符串:ACEGHI 和 BCDEFGH
LCS二维表格
3.设计
def lcs(x, y):
m = len(x) + 1
n = len(y) + 1
if m == 1 or n == 1:
print("存在空字符串!")
return -1
lcs_len = numpy.zeros((m,n))
for i in range(1, m):
for j in range(1, n):
if (x[i - 1] == y[j - 1]):
for j in range(1, n):
if (x[i - 1] == y[j - 1]):
lcs_len[i][j] = lcs_len[i - 1][j - 1] + 1
else:
max_len = lcs_len[i - 1][j]
if lcs_len[i][j - 1] > lcs_len[i - 1][j]:
max_len = lcs_len[i][j - 1]
lcs_len[i][j] = max_len
i = m - 2
j = n - 2
ns = ''
while 1:
if i == -1 or j == -1:
break
if x[i] == y[j]:
ns= x[i]+ns
i = i - 1
j = j - 1
else:
if lcs_len[i][j + 1] > lcs_len[i + 1][j]:
i = i - 1
else:
j = j - 1
print(ns)
分析
时间复杂度:O(n * m) //n和m为两条字符串的长度