动态规划 最长公共字符串

思想:首先通过构造二维数组,较长字符串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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
[1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0]
6
index: 7
[0, 0, 0, 0, 0, 0, 6, 0, 0, 1, 0]
wilson

list=[[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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

for i in map(max,list):
    print(i)

0
0
1
2
3
4
5
6
0
0
0
1
0
1
0
0
0
0
0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值