大意:给定两个字符串word1和word2,为了使word1变为word2,可以进行增加、删除、替换字符三种操作,请输出操作的最少次数
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[i][j]把word1[0..i-1]转换到word2[0..j-1]的最少操作次数
状态转移方程:
状态转移方程:
(1)如果word1[i-1] == word2[j-1],则令dp[i][j] = dp[i-1][j-1]
(2)如果word1[i-1] != word2[j-1],由于没有一个特别有规律的方法来断定执行何种操作,在增加、删除、替换三种操作中选一种操作次数少的赋值给dp[i][j];
增加操作:dp[i][j] = dp[i][j-1] + 1
删除操作:dp[i][j] = dp[i-1][j] + 1
(2)如果word1[i-1] != word2[j-1],由于没有一个特别有规律的方法来断定执行何种操作,在增加、删除、替换三种操作中选一种操作次数少的赋值给dp[i][j];
增加操作:dp[i][j] = dp[i][j-1] + 1
删除操作:dp[i][j] = dp[i-1][j] + 1
替换操作:dp[i][j] = dp[i-1][j-1] + 1
1 int minDistance(string word1,string word2){ 2 int wlen1 = word1.size(); 3 int wlen2 = word2.size(); 4 5 int**dp = new int*[wlen1 + 1]; 6 for (int i = 0; i <= wlen1; i++) 7 dp[i] = new int[wlen2 + 1]; 8 9 //int dp[maxn][maxn] = { 0 }; 10 for (int i = 0; i <= wlen1; i++) 11 dp[i][0] = i; 12 for (int j = 0; j <= wlen2; j++) 13 dp[0][j] = j; 14 int temp = 0; 15 for (int i = 1; i <= wlen1; i++){ 16 for (int j = 1; j <= wlen2; j++){ 17 if (word1[i - 1] == word2[j - 1])dp[i][j] = dp[i - 1][j-1]; 18 else{ 19 temp = dp[i - 1][j - 1]<dp[i - 1][j] ? dp[i - 1][j - 1] : dp[i - 1][j]; 20 temp = temp < dp[i][j - 1] ? temp : dp[i][j - 1]; 21 dp[i][j] = temp + 1; 22 } 23 } 24 } 25 26 /* 27 for (int i = 0; i <= wlen1; i++) 28 delete[]dp[i]; 29 delete[]dp; 30 */ 31 32 return dp[wlen1][wlen2]; 33 }