1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| func minDistance(word1 string, word2 string) int { memo := make(map[[2]int]int) return dp(memo, word1, word2, len(word1)-1, len(word2)-1) }
func dp(memo map[[2]int]int, word1 string, word2 string, i int, j int) int { if i == -1 { return j + 1 } if j == -1 { return i + 1 }
if val, ok := memo[[2]int{i, j}]; ok { return val }
if word1[i] == word2[j] { v := dp(memo, word1, word2, i-1, j-1) memo[[2]int{i, j}] = v
return v } else {
v1 := dp(memo, word1, word2, i, j-1) + 1 v2 := dp(memo, word1, word2, i-1, j) + 1 v3 := dp(memo, word1, word2, i-1, j-1) + 1
v := min(v1, min(v2, v3)) memo[[2]int{i, j}] = v return v } }
func min(a int, b int) int { if a < b { return a } return b }
|