题目描述:
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
解题思路:
用动态规划的方法解决这道题-最短编辑距离:
用dp[i][j]表示word1的前i项变得和word2的前j项一样需要多少步。用上述三种操作:
1.若i=j, 则需要执行的是替换操作,编辑一次,就可实现dp[i][j] –> d[i+1][j+1];
2.若i>j,则word1需要执行删除操作,编辑一次,就可实现dp[i+1][j] –> d[i+1][j+1];
3.若i 小于j, 则word1需要执行插入操作,编辑一次,就可实现dp[i][j+1] –> d[i+1][j+1];
由于可以在这三个操作中自由选择实现最短编辑距离,故只需要选择dp[i][j],dp[i+1][j],dp[i][j+1]中最小一个,就能实现最小。
我们可以写出状态转移方程: d[i+1][j+1] = min(dp[i][j+1], min(dp[i][j],dp[i+1][j] ) )。
代码:
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.size();
int m = word2.size();
int **dp = new int*[n+1];
for(int i = 0;i < n + 1;i++)
dp[i] = new int[m+1];
//dp边界初始化
for(int i = 0;i < n + 1;i++)
dp[i][0] = i;
for(int i = 0;i < m + 1;i++)
dp[0][i] = i;
//转移方程
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(word1[i] == word2[j]) dp[i+1][j+1] = dp[i][j];
else{
dp[i+1][j+1] = min(dp[i][j+1],min(dp[i+1][j],dp[i][j])) + 1;
}
}
}
int res = dp[n][m];
for(int i = 0;i <= n;i++) delete [] dp[i];
delete [] dp;
return res;
}
};
代码运行结果: