# 72. 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

（1）若前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;

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];
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：72. Edit Distance 最小编辑距离 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)