题目:
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
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size()+1;
int n = word2.size()+1;
vector<vector<int>> s(m, vector<int>(n));
//初始化
for(int i = 1; i < m; i++)
s[i][0] = i;
for(int j = 1; j < n; j++)
s[0][j] = j;
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
if(word1[i-1] == word2[j-1]) {
s[i][j] = s[i-1][j-1];
}
else
s[i][j] =min(min(s[i-1][j]+1, s[i][j-1]+1), s[i-1][j-1]+1);
}
}
return s[m-1][n-1];
}
};
1234

被折叠的 条评论
为什么被折叠?



