// 23 583.两个字符串的删除操作
package main
import "fmt"
func minDistance(word1 string, word2 string) int {
//dp[i][j]表示word1以i-1结尾word2以j-1结尾相同所需的最小步数
dp := make([][]int, len(word1)+1)
for i, _ := range dp {
dp[i] = make([]int, len(word2)+1)
}
//初始化 dp[0][j]=j,dp[i][0]=i
for i := 0; i <= len(word1); i++ {
dp[i][0] = i
}
for j := 0; j <= len(word2); j++ {
dp[0][j] = j
}
//遍历顺序从左往右从上到下
for i := 1; i <= len(word1); i++ {
for j := 1; j <= len(word2); j++ {
if word1[i-1] == word2[j-1] {
dp[i][j] = dp[i-1][j-1] //不删除元素
} else {
//删除word1元素、删除word2元素、删除word1和word2元素
dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+2)
}
}
}
return dp[len(word1)][len(word2)]
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
func main() {
word1 := "leetcode"
word2 := "etco"
res := minDistance(word1, word2)
fmt.Printf("res: %v\n", res)
}
// 24 72.编辑距离
package main
import "fmt"
func minDistance(word1 string, word2 string) int {
//dp[i][j]表示word1以i-1结尾word2以j-1结尾转换所需的最小步数
dp := make([][]int, len(word1)+1)
for i, _ := range dp {
dp[i] = make([]int, len(word2)+1)
}
//初始化 dp[0][j]=j,dp[i][0]=i
for i := 0; i <= len(word1); i++ {
dp[i][0] = i
}
for j := 0; j <= len(word2); j++ {
dp[0][j] = j
}
//遍历顺序从左往右从上到下
for i := 1; i <= len(word1); i++ {
for j := 1; j <= len(word2); j++ {
if word1[i-1] == word2[j-1] {
dp[i][j] = dp[i-1][j-1] //不删除元素,不做任何操作
} else {
//删除word1元素或删除word2元素(删除和增加本质是一样的)或替换word1和word2元素
dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+1)
}
}
}
return dp[len(word1)][len(word2)]
}
func min(a, b, c int) int {
if a < b && a < c {
return a
}
if b < c && b < a {
return b
}
return c
}
func main() {
word1 := "horse"
word2 := "ros"
res := minDistance(word1, word2)
fmt.Printf("res: %v\n", res) //res: 3
}