Use a matrix to record the correspondence between the characters in each of the two substrings.
Oldest string : The largest number in the matrix is the length of the oldest string. If the corresponding position character is the same, then c[i][j] = c[i-1][j-1] + 1
1 deflongsubstr (STR1,STR2):2Len1 =Len (str1)3Len2 =Len (str2)4Longest,start1,start2 =0,0,05c = [[0 forIinchRange (len2+1)] forIinchRange (len1+1)]6 forIinchRange (len1+1):7 forJinchRange (len2+1):8 ifi = = 0orj = =0:9C[I][J] =0Ten elifStr1[i-1] = = Str2[j-1]: OneC[I][J] = c[i-1][j-1]+1 A Else: -C[I][J] =0 - if(Longest <C[i][j]): theLongest =C[i][j] -Start1 = iLongest -Start2 = JLongest - + returnStr1[start1:start1+longest],start1,start2
Oldest sequence : if the corresponding position character is the same, then c[i][j] = c[i-1][j-1] + 1, if different, then Max (C[i][j-1],c[i-1][j]).
1 defPrintlcs (flag,a,i,j):2 ifI==0orj==0:3 return 4 ifflag[i][j]=='OK': 5Printlcs (flag,a,i-1,j-1) 6 PrintA[i-1],7 elifflag[i][j]==' Left': 8Printlcs (flag,a,i,j-1) 9 Else: TenPrintlcs (flag,a,i-1, J) One A defLongsubseq (STR1,STR2): -Len1 =Len (str1) -Len2 =Len (str2) theLongest =0 -c = [[0 forIinchRange (len2+1)] forIinchRange (len1+1)] -flag = [[0 forIinchRange (len2+1)] forIinchRange (len1+1)] - forIinchRange (len1+1): + forJinchRange (len2+1): - ifi = = 0orj = =0: +C[I][J] =0 A elifStr1[i-1] = = Str2[j-1]: atC[I][J] = c[i-1][j-1]+1 -FLAG[I][J] ='OK' -Longest =Max (Longest,c[i][j]) - elifC[i][j-1] > C[i-1][j]: -C[I][J] =c[i][j-1] -FLAG[I][J] =' Left' in Else: -C[I][J] =c[i-1][j] toFLAG[I][J] =' up' + Printlcs (FLAG,STR1,LEN1,LEN2) - returnLongest theA='Abcbdab' *b='Bdcaba' $ PrintLongsubseq (A, B)
The python implementation of the longest common substring and subsequence, with illustration.