Scribbling

LeetCode: 72. Edit Distance 본문

Computer Science/Coding Test

LeetCode: 72. Edit Distance

focalpoint 2021. 9. 26. 19:44

 

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m, n = len(word1), len(word2)
        dp = [[0] * (m+1) for _ in range(n+1)]
        for i in range(1, m+1):
            dp[0][i] = i
        for i in range(1, n+1):
            dp[i][0] = i
        for i in range(1, n+1):
            for j in range(1, m+1):
                if word1[j-1] != word2[i-1]:
                    dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
                else:
                    dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]+1, dp[i][j-1]+1)
        return dp[n][m]

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 74. Search a 2D Matrix  (0) 2021.09.28
LeetCode: 73. Set Matrix Zeroes  (0) 2021.09.28
LeetCode: 71. Simplify Path  (0) 2021.09.26
LeetCode: 69. Sqrt(x)  (0) 2021.09.26
LeetCode: 67. Add Binary  (0) 2021.09.26