mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-08 02:15:01 +08:00
32 lines
598 B
Go
32 lines
598 B
Go
package leetcode
|
|
|
|
func minDistance(word1 string, word2 string) int {
|
|
dp := make([][]int, len(word1)+1)
|
|
for i := 0; i < len(word1)+1; i++ {
|
|
dp[i] = make([]int, len(word2)+1)
|
|
}
|
|
for i := 0; i < len(word1)+1; i++ {
|
|
dp[i][0] = i
|
|
}
|
|
for i := 0; i < len(word2)+1; i++ {
|
|
dp[0][i] = i
|
|
}
|
|
for i := 1; i < len(word1)+1; i++ {
|
|
for j := 1; j < len(word2)+1; j++ {
|
|
if word1[i-1] == word2[j-1] {
|
|
dp[i][j] = dp[i-1][j-1]
|
|
} else {
|
|
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j])
|
|
}
|
|
}
|
|
}
|
|
return dp[len(word1)][len(word2)]
|
|
}
|
|
|
|
func min(x, y int) int {
|
|
if x < y {
|
|
return x
|
|
}
|
|
return y
|
|
}
|