1袖扛、題目描述
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')
2、問題描述:
- 求兩個(gè)字符串如何變成一樣的馋劈,最少的步驟攻锰,典型的動(dòng)態(tài)規(guī)劃問題。
3妓雾、問題關(guān)鍵:
-
對于當(dāng)前比較的兩個(gè)字符 word1[i] 和 word2[j]娶吞,若二者相同,一切好說械姻,直接跳到下一個(gè)位置妒蛇。若不相同,有三種處理方法楷拳,首先是直接插入一個(gè) word2[j]绣夺,那么 word2[j] 位置的字符就跳過了,接著比較 word1[i] 和 word2[j+1] 即可欢揖。第二個(gè)種方法是刪除陶耍,即將 word1[i] 字符直接刪掉,接著比較 word1[i+1] 和 word2[j] 即可她混。第三種則是將 word1[i] 修改為 word2[j]烈钞,接著比較 word1[i+1] 和 word[j+1] 即可。
- 狀態(tài)表示:f[i][j] 表示word1的 前i個(gè)字符變成word2的前j個(gè)字符坤按,最少需要操作數(shù)毯欣。
- 狀態(tài)轉(zhuǎn)移:四種情況:
1.如果word1[i] == word2[j],則其操作數(shù)為f[i-1][j - 1];
2.將word1[i]修改word2[j]為一樣的,則操作數(shù)為:f[i - 1][j -1] + 1;
3.將word1[i] 刪除臭脓,則其操作次數(shù)等于f[i - 1][j] + 1;
4.將word1[i]前word2[j],則其i操作數(shù)等于f[i][j - 1] + 1;
時(shí)間復(fù)雜度.
4酗钞、C++代碼:
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(), n = word2.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 0; i <= m; ++i) dp[i][0] = i;
for (int i = 0; i <= n; ++i) dp[0][i] = i;
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(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
}
}
}
return dp[m][n];
}
};