[LeetCode] 72. Edit Distance

题:https://leetcode.com/problems/edit-distance/description/

题目:

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:

Insert a character
Delete a character
Replace a character
Example 1:

Input: word1 = “horse”, word2 = “ros”
Output: 3
Explanation:
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)
Example 2:

Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)

思路

动态规划,因为里面有个贪心的逻辑。
状态:df(str1,str2) str1转str2的最小操作次数
状态转移方程:
若str1尾字符等于str2尾字符
df(str1,str2)= df(str1-1,str2-1)

若str2尾字符不等于str2尾字符
df(str1,str2) = min(df(str1-1,str2-1),df(str1-1,str2),df(str1,str2-1))+1
min中每个数对应的了一种操作。

本想用C++写,实在是太繁琐,也是自己好久没用C++了,哎
python Code

class Solution:

    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        len1 = len(word1)-1
        len2 = len(word2)-1
        len1,len2 = len(word1)-1,len(word2)-1
        dftable={}
        def df(len1,len2):
            if len1 == -1:
                return len2+1
            if len2 == -1:
                return len1+1

            if (len1,len2) in dftable.keys():
                return dftable[(len1,len2)]

            if word1[len1]==word2[len2]:
                dfvalues =  df(len1-1,len2-1)
            else:
                dfvalues = min(df(len1-1,len2-1),df(len1-1,len2),df(len1,len2-1))+1
            dftable[(len1,len2)] = dfvalues

            return dfvalues

        return df(len1,len2)

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/80426088