Minimum edit cost - golang

topic:

Given two strings str1 and str2, given three integers ic, dc, and rc, which represent inserting, deleting, and replacing a character, respectively, return the minimum cost of editing str1 into str2.

Problem solving method:

dynamic programming. First generate a matrix dp of size (M+1)X(N+1).

Suppose str1="av=b12cd3", str2="abcdf". dp[i][j] represents the minimum cost of editing str1[0:i] into str2[0:j]. The calculation results are as follows:

calculation steps:

1. dp[0][0] means that the cost of editing an empty substring of str1 into an empty substring of str2 is 0

2. The first column of the matrix dp is dp[0:M-1][0], dp[i][0] represents the minimum cost of editing str1[0:i-1] into an empty string, that is, str1[0: The cost of deleting all characters in i-1], so dp[i][0] = dc * i

3. The first row of the matrix is ​​dp[0][0:N-1], dp[0][j] represents the minimum cost of editing the empty string into str2[0:j-1], that is, adding characters to the empty string , so dp[0][j] = ic * j

4. Other positions, calculated from left to right and top to bottom, the value of dp[i][j] may come from the following four situations:

(1) str1[0:i-1] is first edited into str1[0:i-2], that is, the character str1[i] is deleted first, and then str1[0:i-2] is edited into str2[0:j- 1],dp[i-1][j] represents the minimum cost of editing str1[0:i-2] into Stoneman[0:j-1], then dp[i][j] may be equal to dc + dp[ i-1][j]

(2) str1[0:i-1] can be edited into str2[0:j-2] first, then insert the character str2[j-1] into str2[0:j-2], and edit it into str2[0:j -1], dp[i][j-1] represents the minimum cost of editing str1[0:i-1] into str2[0:j-2], then dp[i][[j] may be equal to dp[i] ][j-1] + ic;

  (3) If str1[i-1] != str2[j-1], you can edit str1[0:i-2] into str2[0:j-2] first, and then replace str1[i-1] into str2[j-1], dp[i-1][j-1] represents the minimum cost of editing str1[0:i-2] into str2[0:j-2], then dp[i][j ] may be equal to dp[i-1][j-1]+rc

(4) If str1[i-1] == str2[j-1], then dp[i][j] = dp[i-1][j-1]

The specific code is as follows:

func GetDp(str1, str2 []rune, ic, dc, rc int)int{
    rows := len(str1) + 1
    cols: = len (str2) + 1
    dp := make([][]int, rows)
    for i, _ := range dp {
        dp[i] = make([]int, cols)
    }
    for i:=0;i < cols;i++{
        dp[0][i] = ic * i
    }
    for i:=0;i < rows;i++{
        dp[i][0] = dc * i
    }
    for i:=1;i<rows;i++{
        for j:=1;j<cols;j++{
            if str1[i-1] == str2[j-1]{
                dp[i][j] = dp[i-1][j-1]
            }else{
                dp[i][j] = dp[i-1][j-1] + rc
            }
            dp[i][j] = getMin(dp[i][j], dp[i][j-1]+ic)
            dp[i][j] = getMin(dp[i][j], dp[i-1][j] + dc)
        }
    }
    return dp[rows-1][cols-1]
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325083873&siteId=291194637