(字符串动态规划)一个字符串变成另一个字符串的步骤数
- 题目:
给定两个字word1和word2,找到将word1转换为word2所需的最小步骤数。 (每个操作计为1步)。 您对单词允许以下3种操作: a)插入字符 b)删除字符 c)替换字符
- 思路:
dp[i][j]指把word1[0..i - 1]转换为word2[0..j - 1] 的最小操作数。
边界条件:
dp[i][0] = i; 从长度为 i 的字符串转为空串 要删除 i 次
dp[0][j] = j. 从空串转为长度为 j 的字符串 要添加 j 次一般情况:
如果word[i - 1] == word2[j - 1],则dp[i][j] = dp[i - 1][j - 1],因为不需要进行操作,即操作数为0.
如果word[i - 1] != word2[j - 1],则需考虑三种情况,取最小值:
Replace word1[i - 1] by word2[j - 1]: (dp[i][j] = dp[i - 1][j - 1] + 1 (for replacement));
Delete word1[i - 1]: (dp[i][j] = dp[i - 1][j] + 1 (for deletion));
Insert word2[j - 1] to word1[0..i - 1]: (dp[i][j] = dp[i][j - 1] + 1 (for insertion)). - 代码
class Solution { public: int minDistance(string word1, string word2) { int row = word1.size(); int col = word2.size(); vector<vector<int> >dp(row+1, vector<int>(col+1, 0)); for (int i=1; i<=row; i++) dp[i][0] = i;//从长度为i的字符串到空串需要变换i次 for (int j=1; j<=col; j++) dp[0][j] = j;//从长度为kong的字符串到长度为j的字符串需要变换j次 for (int i=1; i<=row; i++){ for (int j=1; j<=col; j++){ if (word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1]; else dp[i][j] = min(min(dp[i-1][j-1]+1,dp[i-1][j] +1), dp[i][j-1]+1 ); } } return dp[row][col]; } };