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
解答:
给定两个字符串str1,str2. 假设要改变str1,使得其变成str2(操作只在s1上进行). dp[i][j] 表示求s1的前i个和s2的前j个的最小编辑距离。那么有下面三种情况:
(1)若前dp[i-1][j-1]的已经求得,
若s[i] == s[j] 则dp[i][j] =dp[i-1][j-1];
若s[i] != s[j] 则dp[i][j] =dp[i-1][j-1]+1; 将s[i]的值replace成s[j]的值
(2)若dp[i][j-1]的已经求得,则需要insert一个和s2[j]相同的,才能使其两个字符串相等,即
dp[i][j] =dp[i][j-1]+1;
(3)若dp[i-1][j]的已经求得,则只需把s1[i]删除就好 ,即
dp[i][j] =dp[i-1][j]+1;
因此递推公式可由上式得到。
注意:由于对于第一个字符来说,前i-1个是没有字符,没法得到i-1,j-1,故对dp矩阵多加一行一列,表示字符串为空时的情形。
代码如下:
class Solution {
public:
int minDistance(string word1, string word2) {
int count = 0, len1 = word1.size(), len2 = word2.size();
if(len1 == 0 && len2 == 0) return 0;
vector<vector<int>>num(len1+1, vector<int>(len2+1,0));
for(int i = 1; i <= len2; i++){
num[0][i] = i;
}
for(int j = 1; j <= len1; j++)
num[j][0] = j;
for(int i = 1; i <= len1; i++){
for(int j = 1; j <= len2; j++){
if(word1[i-1] == word2[j-1])
num[i][j] = num[i-1][j-1];
else
num[i][j] = num[i-1][j-1]+1;
num[i][j] = min(num[i][j],min(num[i-1][j], num[i][j-1])+1);
}
}
return num[len1][len2];
}
};