fork download
  1. class Solution:
  2. def editDistance(self, word1: str, word2: str) -> int:
  3. #dp[i][j] will be the least distance from word1[:i] to word2[:j]
  4. dp = [[0 for _ in range(len(word2)+1)] for _ in range(len(word1)+1)]
  5. for i in range(len(word1)+1):
  6. dp[i][0] = i
  7. for j in range(1,len(word2)+1):
  8. if i == 0:
  9. dp[0][j] = j
  10. elif word1[i-1] == word2[j-1]:
  11. dp[i][j] = dp[i-1][j-1]
  12. else:
  13. dp[i][j] = min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1
  14. return dp[-1][-1]
  15.  
  16. obj = Solution()
  17. str1 = "saturday"
  18. str2 = "sunday"
  19. print(obj.editDistance(str1, str2))
Success #stdin #stdout 0.03s 9544KB
stdin
Standard input is empty
stdout
3