72-Edit distance-python

Given two words  word1  and  word2 , calculate  the minimum number of operands used to convert  word1  to  word2 .

You can perform the following three operations on a word: 1. Insert a character 2. Delete a character 3. Replace a character

def min_distance(word1,word2):
    word1_len, word2_len = len(word1), len(word2)
    dp = [[0] * (word2_len + 1) for _ in range(word1_len + 1)]
    for i in range(1, word1_len + 1):
        dp[i][0] = i
    for j in range(1, word2_len + 1):
        dp[0][j] = j

    for i in range(1, word1_len + 1):
        for j in range(1, word2_len + 1):
            if  word1[i - 1] == word2[j - 1]:
                dp[i][j] = dp[i-1][j-1]
            else:
                dp[i][j] = min(dp[i - 1][j - 1] + 1, dp[i][j - 1] + 1, dp[i - 1][j] + 1)

    return dp[-1][-1]

  Note: Use the idea of ​​dynamic programming. The state equation is:

f(i,j) represents the minimum steps required to convert word1[:i] to word2[:j]

 

Guess you like

Origin blog.csdn.net/wh672843916/article/details/105503752