问题描述:
https://oj.leetcode.com/problems/edit-distance/点击打开链接
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
问题分析:
定义:
f[i][j] :长度为i 的字符串s1 长度为j 的字符串s2的最小编辑距离。
初始化:
推导:
s1[i] == s2[j] f[i][j] = f[i - 1][j - 1];
s1[i] != s2[j] f[i][j] = min { f[i - 1][j - 1] + 1, f[i][j - 1] + 1, f[i - 1][j] + 1}
示例代码:
class Solution {
public:
int minDistance(string word1, string word2)
{
#define MAX_LEN (500 + 1)
int f[MAX_LEN][MAX_LEN] = { 0 };
int m, n, i, j;
m = word1.length();
n = word2.length();
for (i = 1; i <= m; i++)
{ f[i][0] = i; }
for (i = 1; i <= n; i++)
{ f[0][i] = i; }
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
if (word1[i - 1] == word2[j - 1])
{ f[i][j] = f[i - 1][j - 1]; }
else
{
int tmp = min(min(f[i][j - 1], f[i - 1][j]), f[i - 1][j - 1]);
f[i][j] = tmp + 1;
}
}
}
return f[m][n];
}
};