典型的编辑距离问题,就是dp问题。
class Solution {
public:
int minDistance(string word1, string word2) {
word1 = ";"+word1;
word2 = ";"+word2;
vector<int> temp(word2.size(), 0);
vector<vector<int>> res(word1.size(), temp);
for(int i=0;i< word1.size();i++){
res[i][0]=i;
}
for(int i=0;i< word2.size();i++){
res[0][i]=i;
}
for(int i=1;i<word1.size();i++){
for(int j=1;j<word2.size();j++){
if(word1[i]==word2[j]){
res[i][j]=res[i-1][j-1];
}
else{
int b1 = res[i-1][j-1] + 1;
int b2 = res[i-1][j] + 1;
int b3 = res[i][j-1] + 1;
int min = b1;
if (b2 < min){min=b2;}
if (b3 < min){min=b3;}
res[i][j] = min;
}
}
}
return res[word1.size()-1][word2.size()-1];
}
};