/*动态规划法。
用dp[i][j]表示word1[i...m],word[j...n]的距离(m,n分别表示其最后一个元素)。
1)若word1[i] == word2[j],则有dp[i][j] = dp[i+1][j+1];
2)若word1[i] != word2[j], 则有dp[i][j] = min{
dp[i+1][j+1]+1(这种情况是用word1[i]代替word2[j]或用word2[j]代替word1[i]),
dp[i][j+1]+1(这种情况是删掉word2[j]或者在word1[i]之前插入word2[j])
dp[i+1][j]+1(这种情况是删掉word1[i]或者在word2[j]之前插入word1[i])
}
最后返回dp[0][0].时间空间复杂度都是O(n^2).*/
class Solution {
public:
int minDistance(string word1, string word2) {
if(word1.empty()) return word2.size();
if(word2.empty()) return word1.size();
vector<vector<int> > dp(word1.size()+1, vector<int>(word2.size()+1, 0));
for(int i = 0; i < word2.size()+1; ++i){
dp[word1.size()][i] = word2.size() - i;
}
for(int i = 0; i < word1.size()+1; ++i){
dp[i][word2.size()] = word1.size() - i;
}
for(int i = word1.size()-1; i >= 0; --i){
for(int j = word2.size()-1; j >= 0; --j){
if(word1[i] == word2[j]) dp[i][j] = dp[i+1][j+1];
else{
int tmp = min(dp[i+1][j]+1, dp[i][j+1]+1);
dp[i][j] = min(tmp, dp[i+1][j+1]+1);
}
}
}
return dp[0][0];
}
};
LeetCode 之Edit Distance
最新推荐文章于 2020-06-02 09:57:27 发布