当前位置:   article > 正文

Golang | Leetcode Golang题解之第72题编辑距离_编辑距离 golang

编辑距离 golang

题目:

题解:

  1. func minDistance(word1 string, word2 string) int {
  2. m, n := len(word1), len(word2)
  3. dp := make([][]int, m+1)
  4. for i := range dp {
  5. dp[i] = make([]int, n+1)
  6. }
  7. for i := 0; i < m+1; i++ {
  8. dp[i][0] = i // word1[i] 变成 word2[0], 删掉 word1[i], 需要 i 部操作
  9. }
  10. for j := 0; j < n+1; j++ {
  11. dp[0][j] = j // word1[0] 变成 word2[j], 插入 word1[j],需要 j 部操作
  12. }
  13. for i := 1; i < m+1; i++ {
  14. for j := 1; j < n+1; j++ {
  15. if word1[i-1] == word2[j-1] {
  16. dp[i][j] = dp[i-1][j-1]
  17. } else { // Min(插入,删除,替换)
  18. dp[i][j] = Min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1
  19. }
  20. }
  21. }
  22. return dp[m][n]
  23. }
  24. func Min(args ...int) int {
  25. min := args[0]
  26. for _, item := range args {
  27. if item < min {
  28. min = item
  29. }
  30. }
  31. return min
  32. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/850374
推荐阅读
相关标签
  

闽ICP备14008679号