#72 Edit Distance——Top 100 Liked Questions

妖狐艹你老母 2022-01-29 03:09 348阅读 0赞

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

  1. Input: word1 = "horse", word2 = "ros"
  2. Output: 3
  3. Explanation:
  4. horse -> rorse (replace 'h' with 'r')
  5. rorse -> rose (remove 'r')
  6. rose -> ros (remove 'e')

Example 2:

  1. Input: word1 = "intention", word2 = "execution"
  2. Output: 5
  3. Explanation:
  4. intention -> inention (remove 't')
  5. inention -> enention (replace 'i' with 'e')
  6. enention -> exention (replace 'n' with 'x')
  7. exention -> exection (replace 'n' with 'c')
  8. exection -> execution (insert 'u')

“””

第一次:动态规划,分插入:d[i-1][j]+1,删除:d[i][j-1]+1,替换:d[i-1][j-1] + (word1[i-1] != word2[i-1])三种情况
“””

  1. class Solution(object):
  2. def minDistance(self, word1, word2):
  3. """
  4. :type word1: str
  5. :type word2: str
  6. :rtype: int
  7. """
  8. m = len(word1)
  9. n = len(word2)
  10. if m == 0:
  11. return n
  12. if n == 0:
  13. return m
  14. dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
  15. for i in range(m + 1):
  16. dp[i][0] = i
  17. for j in range(n + 1):
  18. dp[0][j] = j
  19. for i in range(1, m + 1):
  20. for j in range(1, n + 1):
  21. dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (word1[i - 1] != word2[j - 1]))
  22. return dp[m][n]

“””

Runtime: 164 ms, faster than 57.95% of Python online submissions for Edit Distance.

Memory Usage: 14.9 MB, less than 53.46% of Python online submissions for Edit Distance.

“””

发表评论

表情:
评论列表 (有 0 条评论,348人围观)

还没有评论,来说两句吧...

相关阅读