描述
问一个字符串需要多少的操作才能变成另一个字符串
解决
动态规划
class Solution {
public:
int minDistance(string word1, string word2) {
int length1 = word1.size();
int length2 = word2.size();
vector<vector<int>> dp(length1 + 1, vector<int>(length2 + 1, 0));
for (int i = 0; i <= length1; ++i)
dp[i][0] = i;
for (int j = 0; j <= length2; ++j)
dp[0][j] = j;
for (int i = 0; i < length1; ++i)
{
for (int j = 0; j < length2; ++j)
{
int cost = word1[i] == word2[j] ? 0 : 1;
dp[i + 1][j + 1] = min(min(dp[i][j + 1] + 1, dp[i + 1][j] + 1), dp[i][j] + cost);
}
}
return dp[length1][length2];
}
};