给定两个字符串str1和str2,再给定三个整数ic,dc和rc,分别代表插入、删除和替换一个字符的代价,请输出将str1编辑成str2的最小代价。
数据范围:,
要求:空间复杂度 ,时间复杂度
go实现:
func minEditCost(str1 string, str2 string, ic int, dc int, rc int) int { n1, n2 := len(str1), len(str2) dp := make([][]int, n1+1) for i := 0; i <= n1; i++ { dp[i] = make([]int, n2+1) } for i := 1; i <= n1; i++ { dp[i][0] += dp[i-1][0] + dc } for j := 1; j <= n2; j++ { dp[0][j] += dp[0][j-1] + ic } for i := 1; i <= n1; i++ { for j := 1; j <= n2; j++ { if str1[i-1] == str2[j-1] { dp[i][j] = dp[i-1][j-1] continue } dp[i][j] = min(dp[i-1][j]+dc, dp[i][j-1]+ic) dp[i][j] = min(dp[i][j], dp[i-1][j-1]+rc) } } return dp[n1][n2] } func min(a, b int) int { if a > b { return b } return a }