zoukankan      html  css  js  c++  java
  • 动态规划——计算两个单词的最短距离

    题目描述:

    给出两个单词word1和word2,计算出将word1 转换为word2的最少操作次数。

    你总共三种操作方法:

    • 插入一个字符
    • 删除一个字符
    • 替换一个字符

    思路:

    首先定义这样一个函数——edit(i, j),它表示第一个字符串的长度为i的子串到第二个字符串的长度为j的子串的编辑距离。

    显然可以有如下动态规划公式:

    • if i == 0 且 j == 0,edit(i, j) = 0
    • if i == 0 且 j > 0,edit(i, j) = j
    • if i > 0 且j == 0,edit(i, j) = i
    • if i ≥ 1  且 j ≥ 1 ,edit(i, j) == min{ edit(i-1, j) + 1, edit(i, j-1) + 1, edit(i-1, j-1) + f(i, j) },当第一个字符串的第i个字符不等于第二个字符串的第j个字符时,f(i, j) = 1;否则,f(i, j) = 0。

     

     计算edit(1, 1),edit(0, 1) + 1 == 2,edit(1, 0) + 1 == 2,edit(0, 0) + f(1, 1) == 0 + 1 == 1,min(edit(0, 1),edit(1, 0),edit(0, 0) + f(1, 1))==1,因此edit(1, 1) == 1。 依次类推:

     代码实现:

    # s1 = 'failing'
    # s2 = 'sailn'
    s1 = input()
    s2 = input()
    l1 = len(s1)
    l2 = len(s2)
    table = [[0 for column in range(l1+1)] for raw in range(l2+1)]
    
    for column in range(l1+1):
        table[0][column]=column
    for raw in range(l2+1):
        table[raw][0] = raw
    for raw in range(1,l2+1):
        for column in range(1,l1+1):
            c1 = table[raw-1][column]+1
            c2 = table[raw][column-1]+1
            if s1[column-1] == s2[raw-1]:
                c3 = table[raw-1][column-1]
            else:
                c3 = table[raw-1][column-1]+1
            table[raw][column]=min([c1,c2,c3])
    # for i in range(l2+1):
    #     print(table[i])
    print(table[-1][-1])
  • 相关阅读:
    INFORMATION_SCHEMA.INNODB_LOCKS
    INFORMATION_SCHEMA.INNODB_TRX 详解
    zabbix 通过key 获取
    匿名hash
    [] 和{} 匿名引用
    perl 初始化Hash
    9.2 数组的散列
    数组的数组
    RMAN恢复目录
    验证备份前设置CONFIGURE CONTROLFILE AUTOBACKUP ON/OFF; 的区别
  • 原文地址:https://www.cnblogs.com/sunny0824/p/13616565.html
Copyright © 2011-2022 走看看