难度:Hard
描述:
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
思路:课上讲过,复习一下。
需要找出word1到word2的编辑距离。
dp[i][j]状态转移如下情况:
1.从dp[i-1][j-1]转移而来,如果最新的两个字符相同,就不需要替换字符,dp[i-1][j-1]+0,否则+1
2.从dp[i-1][j]转移而来,为了处理加上的这个字符,dp[i-1][j]+1 对应的操作是word1串长度不够,要+1
3.从dp[i][j-1]转移而来,为了处理加上的这个字符,dp[i][j-1]+1 对应的操作是word1串长度过长,要-1
dp[i][j] = min{1.,2.,3.}
如果画一个表格来填写,模拟这个过程,可以清楚看到算法的意图。
代码:
class Solution {
public:
int minDistance(string word1, string word2) {
int dp[1000][1000];
int m = word1.size();
int n = word2.size();
for (int i = 0; i <= m; i++){
dp[i][0] = i;
}
for (int i = 0; i <= n; i++){
dp[0][i] = i;
}
for (int i = 1; i <= m; i++){
for (int j = 1; j<=n; j++){
int min = 99999;
int bonus = 0;
if (word1[i-1] != word2[j-1]) bonus = 1;
if (dp[i-1][j-1] < min) min = dp[i-1][j-1]+bonus;
if (dp[i][j-1] < min) min = dp[i][j-1]+1;
if (dp[i-1][j] < min) min = dp[i-1][j]+1;
dp[i][j] = min;
}
}
return dp[m][n];
}
};