LeetCode 72. Edit Distance

亦凉 2023-06-04 04:58 103阅读 0赞

题目

简单动态规划

  1. class Solution {
  2. public:
  3. int dp[1005][1005];
  4. int minDistance(string word1, string word2) {
  5. int len1=word1.length();
  6. int len2=word2.length();
  7. if(len1==0)
  8. return len2;
  9. if(len2==0)
  10. return len1;
  11. for(int i=0;i<len1;i++)
  12. {
  13. for(int j=0;j<len2;j++)
  14. {
  15. dp[i][j]=99999;
  16. if(i==0&&j==0)
  17. {
  18. if(word1[i]==word2[j])
  19. {
  20. dp[i][j]=0;
  21. }
  22. else
  23. dp[i][j]=1;
  24. continue;
  25. }
  26. if(i>0)
  27. dp[i][j]=min(dp[i][j],dp[i-1][j]+1);
  28. if(j>0)
  29. dp[i][j]=min(dp[i][j],dp[i][j-1]+1);
  30. if(i>0&&j>0)
  31. dp[i][j]=min(dp[i][j],dp[i-1][j-1]+1);
  32. if(word1[i]==word2[j])
  33. {
  34. if(i>0&&j>0)
  35. dp[i][j]=min(dp[i][j],dp[i-1][j-1]);
  36. if(i==0)
  37. {
  38. dp[i][j]=min(dp[i][j],j);
  39. }
  40. if(j==0)
  41. dp[i][j]=min(dp[i][j],i);
  42. }
  43. }
  44. }
  45. return dp[len1-1][len2-1];
  46. }
  47. };

转载于:https://www.cnblogs.com/dacc123/p/11619008.html

发表评论

表情:
评论列表 (有 0 条评论,103人围观)

还没有评论,来说两句吧...

相关阅读