编辑距离

https://leetcode-cn.com/problems/edit-distance/description/

思路如下:

计算编辑距离

: : : : : :
- - a d i t
- 0 1 2 3 4
e 1 1
d 2
a 3
t 4
x 5

old(记录左上角的值)
动态规划的思路很简单, 倒推

python代码

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        len1, len2 = len(word1), len(word2)
        if len1 == 0 or len2 == 0:
            return max(len1, len2)
        dp = [[0] * (len2 + 1) for _ in range(len1 + 1)] # len1行 len2列
        for i in range(len1 + 1):
            dp[i][0] = i;
        for j in range(len2 + 1):
            dp[0][j] = j
            
        for i in range(1, len1 + 1):
            for j in range(1, len2 + 1):
                if(word1[i-1] == word2[j-1]):
                    dp[i][j] = dp[i-1][j-1];
                else:
                    dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1

        return dp[len1][len2]

scala代码


// 计算编辑距离
  /*
        a d i t    old(记录左上角的值, pw(0) 更新为)
      0 1 2 3 4
    e 1 1           0
    d 2
    a 3
    t 4
    x
  */

object Solution {
    def minDistance(x: String, y: String): Int = {
        val pw = new Array[Int](y.length + 1)
        for(j <- Range(0, y.length + 1)) pw(j) = j
        for(i <- Range(1, x.length + 1))
        {
            var old = i - 1 // 初始左上角的值是i - 1
            pw(0) = i   // 初始最左边的值是 i, 最上面的值是 j  x初始最左边的值
            for(j <- Range(1, y.length + 1)){
              val temp = pw(j)
              if(x(i - 1) == y(j - 1)){
                  pw(j) = old
              }
              else{
                  pw(j) = math.min(math.min(pw(j) + 1, pw(j-1) + 1), old + 1)
              }
              old = temp // pw(j)更新后, old替换为pw(j)原来的值,也就是左上角的值
              }
        }
        pw(y.length)
    }
}

推荐阅读更多精彩内容