Total Accepted: 55602
Total Submissions: 195784
Difficulty: Hard
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2.
(each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
Subscribe to see which companies asked this question
Show Similar Problems
显然采用动态规划做:
用dp[n+1][m+1]表示需要执行的最少变换次数,则递推方程为:
- dp[i+1][j+1] = dp[i][j], 当word1[i] == word2[j]
- dp[i + 1][j + 1] = min(min(dp[i][j] + 1, dp[i][j + 1] + 1), dp[i + 1][j] + 1); 当word1[i] != word2[j]
class Solution
{
public:
int minDistance(string word1, string word2)
{
int len1 = word1.size(), len2 = word2.size();
vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1));
// 左边沿初始化
for (int i = 0; i <= len1; ++i)
dp[i][0] = i;
// 右边沿初始化
for (int i = 0; i <= len2; ++i)
dp[0][i] = i;
for (int i = 0; i < len1; ++i)
{
for (int j = 0; j < len2; ++j)
{
if (word1[i] == word2[j])
dp[i + 1][j + 1] = dp[i][j];
else
dp[i + 1][j + 1] = min(min(dp[i][j] + 1, dp[i][j + 1] + 1), dp[i + 1][j] + 1);
}
}
return dp[len1][len2];
}
};