Skip to content

Latest commit

 

History

History
90 lines (76 loc) · 2.27 KB

072.md

File metadata and controls

90 lines (76 loc) · 2.27 KB

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:

Insert a character Delete a character 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[i][j]为 word1[0:i] --> word2[0:j]的最少操作次数 
    (对于word1 = "horse" word1[0:0] = "", word[0:1] = "h")
    ②由①得出dp[0][j] = j (其中j>=0.j<=len(word2)) 该行的意义为 word1[0:0]-->word2[0:j]最少操作次数
            dp[i][0] = i (其中i>=0.i<=len(word1)) 该行的意义为 word1[0:i]-->word2[0:0]最少操作次数
    ③通项公式:
        if word1[i] == word[j] 
            dp[i][j] = dp[i-1][j-1]
        else 
            dp[i][j] = Min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1
           insert operation^^^^^^^^^^
                       delete operation^^^^^^^^^^ 
                                  replace operation^^^^^^^^^^^^^

代码

func minDistance(word1 string, word2 string) int {
    dp := make([][]int,len(word1)+1)
    row, col := 0, 0
    for row = 0; row <= len(word1); row++ {
        temp := make([]int, len(word2)+1)
        dp[row] = temp
        dp[row][0] = row
    }
    for col = 0; col < len(word2); col++ {
        dp[0][col+1] = col + 1
    }
    for row = 1; row <= len(word1); row++ {
        for col = 1; col <= len(word2); col++ {
            if word1[row-1] == word2[col-1] {
                dp[row][col] = dp[row-1][col-1]
                continue
            } 
            dp[row][col] = threeMin(dp[row-1][col], dp[row][col-1], dp[row-1][col-1]) + 1
        }
    }
    //fmt.Println(dp)
    return dp[len(word1)][len(word2)]
}

func threeMin(a, b, c int) int {
    if a > b {
        a = b
    }
    if a < c {
        return a
    } else {
        return c
    }
    
}