大意:给定两个字符串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
int minDistance(string word1,string word2){
int wlen1 = word1.size();
int wlen2 = word2.size(); int**dp = new int*[wlen1 + ];
for (int i = ; i <= wlen1; i++)
dp[i] = new int[wlen2 + ]; //int dp[maxn][maxn] = { 0 };
for (int i = ; i <= wlen1; i++)
dp[i][] = i;
for (int j = ; j <= wlen2; j++)
dp[][j] = j;
int temp = ;
for (int i = ; i <= wlen1; i++){
for (int j = ; j <= wlen2; j++){
if (word1[i - ] == word2[j - ])dp[i][j] = dp[i - ][j-];
else{
temp = dp[i - ][j - ]<dp[i - ][j] ? dp[i - ][j - ] : dp[i - ][j];
temp = temp < dp[i][j - ] ? temp : dp[i][j - ];
dp[i][j] = temp + ;
}
}
} /*
for (int i = 0; i <= wlen1; i++)
delete[]dp[i];
delete[]dp;
*/ return dp[wlen1][wlen2];
}