版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jining11/article/details/83624520
题目要求
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
求解思路
这是一个经典的动态规划问题了,以前做DNA序列比较时也完成过。
假设:
状态转移方程:
状态初始化
源代码
有两点需要注意,一个是字符串的下标需要-1,另一个是diff的实现方式,如果写成我一开始提交的版本即
int(word1[i-1]!=word2[j-1])
,执行速度会非常之慢,还是写成(word1[i-1]!=word2[j-1] ? 1 : 0)
为好
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector <vector <int>> E (m+1, vector<int>(n+1, 0));
for (int i = 0; i < n+1; i++) {
E[0][i] = i;
}
for (int j = 1; j < m+1; j++) {
E[j][0] = j;
}
for (int i = 1; i < m+1; i++) {
for (int j = 1; j < n+1; j++) {
E[i][j] = min(1+min(E[i-1][j], E[i][j-1]), E[i-1][j-1]+(word1[i-1]!=word2[j-1] ? 1 : 0));
}
}
return E[m][n];
}
};
满意了满意了