# Edit Distance(动态规划)

## Edit Distance

### 题目

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

Insert a character
Delete a character
Replace a character
Example 1:

Input: word1 = “horse”, word2 = “ros”
Output: 3
Explanation:
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)
Example 2:

Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)

### 源码

class Solution {
public:
int minDistance(string word1, string word2) {
int size1 = word1.size();
int size2 = word2.size();
vector<vector<int>> count(size1+1, vector<int>(size2+1, 0));
for(int i = 0; i <= size1; i++) {
count[i][0] = i;
}
for(int i = 0; i <= size2; i++) {
count[0][i] = i;
}

for(int i = 1; i <= size1; i++) {
for(int j = 1; j <= size2; j++) {
int tag = 0;
if(word1[i-1] != word2[j-1]) {
tag = 1;
}
count[i][j] = min(count[i-1][j]+1, count[i][j-1]+1);
count[i][j] = min(count[i][j], tag+count[i-1][j-1]);
}
}
return count[size1][size2];
}
};


## 更多技术博客：https://vilin.club/

• 点赞
• 评论 1
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

Vilinzz

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
05-03 1万+
10-11 2万+

08-19 1755
05-22 437
12-31 4万+
12-16 22
09-07 501
05-25 1438