链接
LeetCode题目:https://leetcode.com/problems/edit-distance/
难度:Hard
题目
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
题目大意是算出一个字符串转变为另一个字符串所需的最小步骤,其中增、删、替换一个字符各算一个步骤。
分析
涉及最优子结构问题可以使用动态规划算法。定义minDis[i][j]为word1前i个字符转变为word2前j个字符所需的最小步骤数,初始化minDis[i][0]=i,minDis[0][i]=i。
当word1的第i个字符和word2的第j个字符不相等时,考虑三种情况,第一种是word1前i-1个字符转变为word2前j-1个字符,然后word1第i个字符替换为word2第j个字符;第二种是word1前i-1个字符转变为word2前j个字符,然后删掉word1第i个字符;第三种是word1前i个字符转变为word2前j-1个字符,然后增加word2第j个字符。
而当word1的第i个字符和word2的第j个字符相等时,只需要考虑word1前i-1个字符转变为word2前j-1个字符的最小步骤。
代码
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = (int) word1.size(), len2 = (int) word2.size();
vector<vector<int>> minDis;
for (int i = 0; i <= len1; i++) {
vector<int> temp;
for (int j = 0; j <= len2; j++) {
temp.push_back(0);
}
minDis.push_back(temp);
}
for (int i = 1; i <= len1; i++) {
minDis[i][0] = i;
}
for (int i = 1; i <= len2; i++) {
minDis[0][i] = i;
}
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (word1[i - 1] != word2[j - 1]) {
minDis[i][j] = min(min(minDis[i - 1][j - 1], minDis[i - 1][j]),
minDis[i][j - 1]) + 1;
} else {
minDis[i][j] = minDis[i - 1][j - 1];
}
}
}
return minDis[len1][len2];
}
};