题目:
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three 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')
Constraints:
0 <= word1.length, word2.length <= 500
word1
andword2
consist of lowercase English letters.
思路:
dp题,相当于583. Delete Operation for Two Strings的follow up题,只是变换方式不同。同样,dp[i][j]即使字符串s1 [0, i - 1]截取的字符串和s2 [0, j - 1]截取的字符串相等的情况,需要进行多少次操作。如果当前两个字母相等的话,那就不用操作了,直接dp[i][j] = dp[i - 1][j - 1]即可。如果不同,我们以s1为基点考虑,因为s1和s2是相对的,在s1插入相当于在s2删除,因此我们以s1为基点考虑,就不用再考虑一次在s2上的操作了。如果不同,dp是三种情况,在s1删除一个字符,即s1[i - 1]删掉,那么就来自s1[i - 2]的结果,即dp[i - 1][j];插入一个字符,相当于在s2删除一个字符,即s2[j - 1]删掉,那么就来自dp[i][j - 1] + 1;替换一个字符,那就相当于不删除,则来自dp[i - 1][j - 1] + 1。初始化和583是一样的,从dp定义出发,对于f[i][0]来说,即s1的子串[0, i]删除几次才能和空字符串相同,显然是i次,对于f[0][j]同理。
代码:
class Solution {
public:
int minDistance(string s1, string s2) {
int m = s1.size(), n = s2.size();
vector<vector<int>> f(m + 1, vector<int>(n + 1));
for (int i = 1; i < m + 1; i++)
f[i][0] = i;
for (int j = 1; j < n + 1; j++)
f[0][j] = j;
for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
if (s1[i - 1] == s2[j - 1])
f[i][j] = f[i - 1][j - 1];
else
f[i][j] = min({ f[i - 1][j], f[i][j - 1], f[i - 1][j - 1] }) + 1;
}
}
return f[m][n];
}
};