# 72. Edit Distance 最小编辑距离

67人阅读 评论(0)

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：30328次
• 积分：1917
• 等级：
• 排名：千里之外
• 原创：171篇
• 转载：1篇
• 译文：0篇
• 评论：3条
评论排行
最新评论