【发布时间】:2020-06-14 11:30:06
【问题描述】:
我对下面给出的两个字符串的最长公共子序列问题有一个递归解决方案:
def LCS(i, j, lcs): # i , j are the position of character in X and Y respectively which are being compared
# lcs is the string storing the current longest common subsequence
print(i, j, lcs)
if i == 0 or j == 0: # basic case
return lcs
if X[i - 1] == Y[j - 1]: # increment lcs
lcs = X[i - 1] + lcs
return lcs
# else check for LCS(i-1,j) and LCS(i,j-1)
lcs_copy = str(lcs)
lcs1 = LCS(i - 1, j, lcs_copy)
x = len(lcs1)
lcs_copy = str(lcs)
lcs2 = LCS(i, j - 1, lcs_copy)
y = len(lcs2)
if x > y:
lcs = lcs1
else:
lcs = lcs2
return lcs
X = 'abcbddab'
Y = 'bdcaba'
lcs = ''
lcs = LCS(8, 6, lcs)
print(lcs)
但它没有给出预期的结果。有什么建议可能是问题所在?
【问题讨论】:
-
似乎对基本情况进行了更正,这将提供最长的公共子序列而不是最长的公共子字符串,即modification of
-
@DarrylG ,我的错,我应该提到问题中的最长公共子序列。实际上,这并没有给出最长的公共子序列。
标签: python algorithm longest-substring