题目如下:
解题思路:一般这种求最大/最小的题目大多数都是用动态规划。记dp[i][j] = n 表示最少经过n次删除操作后,使得word1[0~i]与word2[0~j]相等。那么可以等到递推关系式,如果word1[i] == word2[j],那么dp[i][j] = dp[i-1][j-1];如果不相等,要么删除word1[i],要么删除word2[j],那么dp[i][j] = min(dp[i-1][j],dp[i][j-1])+1。
代码如下:
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ if len(word1) == 0 or len(word2) == 0: return abs(len(word2) - len(word1)) dp = [[0 for x in range(len(word2)+1)] for x in range(len(word1)+1)] for i in xrange(1,len(word1)+1):
#如果word2是空,表示应该删除word1里面全部的字符,所以记dp[i][0] = i dp[i][0] = i for j in xrange(1,len(word2)+1): dp[0][j] = j for i in xrange(1,len(word1)+1): for j in xrange(1,len(word2)+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],dp[i][j-1])+1 return dp[-1][-1]