描述
给出两个单词word1和word2,计算出将word1 转换为word2的最少操作次数。
你总共三种操作方法:
- 插入一个字符
- 删除一个字符
- 替换一个字符
动态规划问题,
当进行一步操作后,将A[2...lenA] B[2...lenB]变成相等字符串
当进行一步操作后,将A[1...lenA] B[2...lenB]变成相等字符串
当进行一步操作后,将A[2...lenA] B[1...lenB]变成相等字符串
dp[i][j]表示当前字符串Ai和Bj的最小不匹配数。
dp[i][j] = dp[i-1][j-1] (A[i] == B[j])
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) (A[i] != B[j])
class Solution { public: /** * @param word1: A string * @param word2: A string * @return: The minimum number of steps. */ int minDistance(string &word1, string &word2) { // write your code here int m = word1.size(), n = word2.size(); vector<vector<int>> dp(m+1, vector<int>(n+1, 0)); for (int i = 1; i <= m; ++i) { dp[i][0] = i; } for (int j = 1; j <= n; ++j) { dp[0][j] = j; } for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1]; else dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1])+1; } } return dp[m][n]; } };