583.delete-operation-for-two-strings.go 635 B

123456789101112131415161718192021222324252627
  1. func minDistance(word1 string, word2 string) int {
  2. // dp[i][j] means the LCS of s1[0:i] && s2[0:j],
  3. // then if s1[i] == s2[j], dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j]+1)
  4. // else dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
  5. m, n := len(word1), len(word2)
  6. dp := make([][]int, m+1)
  7. for i := range dp {
  8. dp[i] = make([]int, n+1)
  9. }
  10. for i := range word1 {
  11. for j := range word2 {
  12. if word1[i] == word2[j] {
  13. dp[i+1][j+1] = maxInt(dp[i+1][j+1], dp[i][j]+1)
  14. } else {
  15. dp[i+1][j+1] = maxInt(dp[i][j+1], dp[i+1][j])
  16. }
  17. }
  18. }
  19. return m + n - 2*dp[m][n]
  20. }
  21. func maxInt(x, y int) int {
  22. if x < y {
  23. return y
  24. }
  25. return x
  26. }