思想:首先通过构造二维数组,较长字符串a作为行,较短字符串b作为列。
将第一行和第一列初始化全初始化为1,
通过递推式,如果当前两个字符串相等,则为左上角的数字加1,否则为0。
找出最大的数字,最大的数字表示公共字符串的长度。
找出公共字符串在字符串a的角标,从后往前数公共字符串个长度即为公共字符串。
word_a="yawilsonafasfs32fda"
word_b="iwilsonolnm"
def sim_word(word_a,word_b):
cell=[[0]*len(word_b) for i in range(len(word_a))]
for i in range(len(word_a)):
for j in range(len(word_b)):
if word_a[i]==word_b[j] and (i<1 or j<1):
cell[i][j]=1
elif word_a[i]==word_b[j]:
cell[i][j]=cell[i-1][j-1]+1
return cell
sw=sim_word(word_a,word_b)
print(sw)
print(max(sw))
print([i for i in (map(max,sw))])
number=max(map(max,sw))
print(number)
index=-1
for line in sw:
if number in line:
index=sw.index(line)
print('index:',index)
break
print(sw[index])
print(word_a[index-number+1:index+1])
结果为:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 5, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 6, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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