题目描述

给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。

示例1

  1. 输入: "sea", "eat"
  2. 输出: 2
  3. 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"

解题思路

  1. class Solution {
  2. public:
  3. int minDistance(string word1, string word2) {
  4. int len1=word1.length(), len2=word2.length();
  5. vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));
  6. for (int j=0; j<=len2; j++)
  7. dp[0][j]=j;
  8. for (int i=0; i<=len1; i++)
  9. dp[i][0]=i;
  10. for (int i=1; i<=len1; i++) {
  11. for (int j=1; j<=len2; j++) {
  12. if (word1[i-1]==word2[j-1])
  13. dp[i][j]=dp[i-1][j-1];
  14. else
  15. dp[i][j]=min(dp[i-1][j], dp[i][j-1])+1;
  16. }
  17. }
  18. return dp[len1][len2];
  19. }
  20. };