题目:
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: (Hard)
a) Insert a character
b) Delete a character
c) Replace a character
分析:
双序列动态规划问题,dp[i][j]表示第一个序列i …和 第二个序列j …;
对应本题:
1. 状态: dp[i][j]表示第一个字符串前i个字符到第二个字符串前j个字符需要的编辑距离;
2. 递推关系:
如果 s1[i] == s2[j]
dp[i][j] = dp[i-1][j-1]
如果 s1[i] != s2[j]
dp[i][j] = min(dp[i-1][j-1] //表示修改
,dp[i-1][j] //表示删除
,dp[i][j-1]) + 1 //表示增加
3. 初始化:
dp[i][0] = i; i = 1…m;
dp[0][j] = j; j = 1…n;
代码:
int minDistance(string word1, string word2) {
int n1 = word1.size(), n2 = word2.size();
vector<vector<int>> dp(n1+1, vector<int>(n2+1, 0));
for(int i = 0; i<= n1; i++)
dp[i][0] = i;
for(int j = 0; j<= n2; j++)
dp[0][j] = j;
for(int i = 1; i<= n1; i++){
for(int j =1; j <= n2; j++){
if(word1[i-1] == word2[j-1])
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1])+1;
}
}
return dp[n1][n2];
}