感想
这是我在牛客网上看到的很经典的一个动态规划的题目,我当时也是不怎么懂,这里我把它记录下来,尽量写详细。
problem
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
code
class Solution {
public:
int minDistance(string word1, string word2) {
int m=word1.length();
int n=word2.length();
// dp[i][j]代表由word1的前i个子串变为word2的前j个子串的花费
vector<vector<int> > dp(m+1,vector<int>(n+1,0));
for(int i=1;i<=m;i++){
dp[i][0]=i; // delete i chars of word1
}
for(int i=1;i<=n;i++){
dp[0][i]=i; // insert i chars of word2
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
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,min(dp[i][j-1]+1,dp[i-1][j-1]+1)); // delete,insert,replace
}
}
}
return dp[m][n];
}
};
分析
dp[i][j]代表由word1的前i个子串变为word2的前j个子串的花费,对应每一种修改方式我们都有不同的状态转移方程
replace: dp[i - 1][j - 1] + 1 //保留从word1的前i-1的次数转变到word2前j-1的次数,然后再加一,加一指的是本次的修改
insert: dp[i][j - 1] + 1 // 保留从word1前i个字符转变到word2的前j-1]的次数,然后加一
delete: dp[i - 1][j] + 1// 保留从word1前i-1个字符转变到word2的前j的次数,加一
总之,如果是替换,前i-1个字符串只能和前j-1个字符串配对,如果需要第i个字符串和第j个字符串配对,就需要+1,替换操作。
如果是插入,前i个字符串只能和前j-1个字符串配对,如果需要跟第j个配对,就需要+1,插入操作
如果是删除,说明前i-1个字符就能和前j个字符串配对,第i个字符是多余的,然后+1,为删除操作。
对于替换插入还是删除,我们选其中最小的值
boundary
从空字符串转换到任意字符串和从任意字符串抓换到空串的操作次数都为改任意字符串的长度(n次插入或n次删除)
dp[i][0] = i;
dp[0][j] = j;
Python实现
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m=len(word1)
n=len(word2)
dp= [[0]*(n+1) for i in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i==0 and j==0:
dp[i][j]=0
elif i==0:
dp[i][j]=j
elif j==0:
dp[i][j]=i
else:
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],dp[i][j-1],dp[i-1][j])+1
return dp[m][n]
参考文献
[1].[编程题]edit-distance.https://www.nowcoder.com/questionTerminal/81d7738f954242e5ade5e65ec40e5027
[2].LeetCode 72. Edit Distance 最短字符串编辑距离 动态规划.https://www.jianshu.com/p/7aa3698096a1