Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u')
感觉这题很厉害,DP , 先领会思想
class Solution { public: int minDistance(string word1, string word2) { int len1 = word1.length(); int len2 = word2.length(); vector<vector<int>> f(len1+1, vector<int>(len2+1, 0)); f[0][0] = 0; // f[i][j] 表示 前 i个数和前j个数 for (int i = 1; i <= len2; ++i) f[0][i] = i; // 即 word1 为空 int temp = 0; for (int j = 1; j <= len1; ++j) f[j][0] = j; // 即word2 为空 for (int i = 1; i <= len1; ++i) { for (int j = 1; j <= len2; ++j) { temp = min(f[i - 1][j] + 1, f[i][j - 1] + 1); if (word1[i - 1] == word2[j - 1]) { f[i][j] = min(temp, f[i-1][j-1]); } else f[i][j] = min(temp, f[i - 1][j - 1] + 1); } } return f[len1][len2]; } int min(int a, int b) { return a > b ? b : a; } };