72.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. func minDistance(word1 string, word2 string) int {
  3. // A classic dp problem. Assume that dp[i][j] is the steps
  4. // that needs to be taken to change w1[0...i-1] into w2[0...j-1],
  5. // then we have dp[i][0] = i (i steps to change len i str into ""),
  6. // and dp[0][j] = j. If we known dp[i-1][j-1], then:
  7. // 1) if w1[i-1] == w2[j-1], dp[i][j] = dp[i-1][j-1];
  8. // 2) if not equal, w1[0...i-1]->w2[0...j-2]->(insert w2[j-1])
  9. // dp[i][j] = dp[i][j-1] + 1
  10. // 3) or (delete w1[i-1])->w1[0...i-2]->w2[0...j-1]
  11. // dp[i][j] = dp[i-1][j] + 1
  12. // 4) or (replace w1[i-1] with w2[j-1])->w1[0...i-2]+w2[j-1]->w2[0...j-2]+w2[j-1]
  13. // dp[i][j] = dp[i-1][j-1] + 1
  14. m, n := len(word1), len(word2)
  15. dp := make([][]int, m+1)
  16. for i := range dp {
  17. dp[i] = make([]int, n+1)
  18. dp[i][0] = i
  19. }
  20. for i := 1; i <= n; i++ {
  21. dp[0][i] = i
  22. }
  23. for i := 1; i <= m; i++ {
  24. for j := 1; j <= n; j++ {
  25. if word1[i-1] == word2[j-1] {
  26. dp[i][j] = dp[i-1][j-1]
  27. } else {
  28. dp[i][j] = minInts(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1
  29. }
  30. }
  31. }
  32. return dp[m][n]
  33. }
  34. // func main() {
  35. // println(minDistance("", ""))
  36. // println(minDistance("horse", "ros"))
  37. // }