class Solution {
public:
int minDistance(string word1, string word2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int M = word1.size();
int N = word2.size();
if(M == 0) return N;
if(N == 0) return M;
vector<vector<int>> f(M+1, vector<int>(N+1, 0));
for(int i = 0; i <= M; i++){
f[i][0] = i;
}
for(int j = 0; j <= N; j++){
f[0][j] = j;
}
for(int i = 1; i <= M; i++){
for(int j = 1; j <= N; j++){
if(word1[i-1] == word2[j-1]){
f[i][j] = min(f[i-1][j]+1, f[i][j-1]+1);
f[i][j] = min(f[i][j],f[i-1][j-1]);
}else{
f[i][j] = min(f[i-1][j]+1, f[i][j-1]+1);
f[i][j] = min(f[i][j],f[i-1][j-1]+1);
}
}
}
return f[M][N];
}
};
[leetcode]Edit Distance
最新推荐文章于 2020-06-22 10:16:26 发布