i am using a list and iterating from last to first element of the strings to find the longest common sub word between them. So the value for the current iteration(LC[i][j]) will depend both on the previous iteration LC[i+1][j+1] and the current matching of the element,
I am facing two issues. - the else statement LC[i][j] = 0 is forcing the element of LC[i+1][j+1] = 0, so if there is a match in the current iteration then LC[i][j] is becoming 1(because LC[i+1][j+1] has been overwritten to 0. - on removing the else statement instead of finding longest common word it is giving longest common sub sequence. please see the output for both the cases
case 1. when else is present.
1st str: zxab enter 2nd str: yzab
i = 3 j = 3 LC[i][j] = 1 LC[i+1][j+1] = 0
i = 2 j = 2 LC[i][j] = 1 LC[i+1][j+1] = 0
i = 0 j = 1 LC[i][j] = 1 LC[i+1][j+1] = 0
max len = 1
case 2. else block removed.
i = 3 j = 3 LC[i][j] = 1 LC[i+1][j+1] = 0
i = 2 j = 2 LC[i][j] = 2 LC[i+1][j+1] = 1
i = 0 j = 1 LC[i][j] = 3 LC[i+1][j+1] = 2
max len = 3
correct answer for max_len should have been 2.
def LCW(u,v):
m = len(u)
n = len(v)
LC = [[0] * (len(v) + 1)] * (len(u) + 1) # create the table one extra due to denote the endng of the word
max_len = 0
for i in range(m-1,-1,-1): # because the strng's last elemnt can be accessed by range(m) == m-1
for j in range(n-1,-1,-1):
if u[i] == v[j]:
LC[i][j] = 1 + LC[i+1][j+1]
#else: LC[i][j] = 0
if max_len < LC[i][j]:
max_len = LC[i][j]
return max_len