Dynamic Programming - 72. Edit Distance

时间:2022-07-25
本文章向大家介绍Dynamic Programming - 72. Edit Distance,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

72. Edit Distance

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u')

思路:

经典dp问题,仔细分析题目会发现,一个串转换为另一个串,无非三种情况,增加删除和替换,状态转移方程就是三者取其中最小的。思想和279、64如出一辙,都是由小算到大。

代码:

go:

func minDistance(word1 string, word2 string) int {
    m, n := len(word1), len(word2)
    
    dp := make([][]int, m+1)
    for i := 0; i < m + 1; i++ {
        dp[i] = make([]int, n+1)
    }
    
    // initialization
    for i := 0; i < m + 1; i++ {
        dp[i][0] = i
    }
    
    for j := 0; j < n + 1; j++ {
        dp[0][j] = j
    } 
    
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if word1[i] == word2[j] {
                dp[i + 1][j + 1] = dp[i][j]
            } else {
                dp[i + 1][j + 1] = min(dp[i][j], min(dp[i + 1][j], dp[i][j+1])) + 1
            }
        }
    }
    
    return dp[m][n]
}

func min (i, j int) int {
    if i < j {
        return i 
    }
    return j
}