我有两个字符串
str1 =“bqdrcvefgh”
str2 =“abcvdefgh”
我想在两个字符串之间找到LCS。但我遇到字符串索引超出范围异常。这是我的代码
str1 = "bqdrcvefgh"
str2 = "abcvdefgh"
#taking str1 as column and str2 as row
lis = [[0]*(len(str1)+1) for i in range(len(str2)+1)]
#The first row and first column has default value of 0
for i in range(1,len(str2)+1):
for j in range(1,len(str1)+1):
if str2[i]==str1[j]:
lis[i][j] = lis[i-1][j-1]+1
else:
lis[i][j] = max(lis[i][j-1],lis[i-1][j])
#length of the longest LCS
print(lis[len(str2)][len(str1)])
我做错了什么?
PS-正确的答案是7
答案 0 :(得分:0)
索引从零开始一直运行到len-1(它从1运行到len运行)。
这里是固定代码:
def lcs(str1, str2):
#taking str1 as column and str2 as row
lis = [[0]*(len(str1)) for i in range(len(str2))]
for i in range(len(str2)):
for j in range(len(str1)):
if str2[i]==str1[j]:
lis[i][j] = lis[i-1][j-1]+1
else:
lis[i][j] = max(lis[i][j-1],lis[i-1][j])
#length of the longest LCS
print(lis[len(str2)-1][len(str1)-1])
str1 = "bqdrcvefgh"
str2 = "abcvdefgh"
lcs(str1, str2) # prints 7