Question
Problem with Longest Common Substring code
Hello,
I'm having an issue with the code from the blog post online about finding the longest common substring. I'm trying to get this code to work, but I'm running into an error.
Here's the code I'm using:
def longestCommonSubstring(str1, str2):
n1 = len(str1)
n2 = len(str2)
table = [[0 for _ in range(n2+1)] for _ in range(n1+1)]
ans = 0
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
if (str1[i-1] == str2[j-1]):
table[i][j] = table[i-1][j-1] + 1
if (table[i][j] > ans):
ans = table[i][j]
else:
table[i][j] = 0
return ans
str1 = "ABCDGH"
str2 = "ACDGHR"
print(longestCommonSubstring(str1, str2))When I run the code, I get the following error:
IndexError: string index out of rangeAny help would be appreciated. Thank you!
