一、问题描述
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
二、思路
采用动态规划求编辑距离。
先给出编辑距离的定义:设A和B是2个字符串,要用最少的字符操作将字符串A转换为字符串B。这里所说的字符操作包括:
(1)删除一个字符(delete);
(2)插入一个字符(insert);
(3)将一个字符改为另一个字符(substitute)。
将字符串A变换为字符串B所用的最少字符操作数称为字符串A到B的编辑距离(edit distance)。
动态规划递归式为:
如果i=0且j=0 edit(0, 0) = 1
如果i=0且j>0 edit(0, j) = edit(0, j-1)+1
如果i>0且j=0 edit(i, 0) = edit(i-1, 0)+1
如果i>0且j>0 edit(i, j) = min(edit(i-1, j)+1, edit(i, j-1)+1, edit(i-1, j-1)+f(i, j) )
其中:edit(i,j)表示S中[0.... i]的子串si到T中[0....j]的子串tj的编辑距离。
f(i,j)表示S中第i个字符s(i)转换到T中第j个字符s(j)所需要的操作次数,如果s(i)==s(j),则不需要任何操作f(i, j)=0; 否则,需要替换操作,f(i, j)=1。
三、代码
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(), n = word2.size();
if (m == 0) return n;
if (n == 0) return m;
int a[m + 1][n + 1];
for(int i = 0; i <= m; ++i) a[i][0] = i;
for(int j = 0; j <= n; ++j) a[0][j] = j;
for(int i = 1; i <= m; ++i)
for(int j = 1; j <= n; ++j){
int f = (word1[i - 1] == word2[j - 1] ? 0 : 1);
a[i][j] = min ( min ( a[i - 1][j] + 1, a[i][j - 1] + 1),a[i - 1][j - 1] + f);
}
return a[m][n];
}
};