LeetCode-583. Delete Operation for Two Strings

网友投稿 546 2022-11-09

LeetCode-583. Delete Operation for Two Strings

LeetCode-583. Delete Operation for Two Strings

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: "sea", "eat"Output: 2Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Note:

The length of given words won't exceed 500.Characters in given words can only be lower-case letters.

题解:

class Solution {public: int minDistance(string word1, string word2) { int l1 = word1.length(), l2 = word2.length(); vector> dp(l1 + 1, vector (l2 + 1, 0)); for (int i = 0; i <= l1; i++) { for (int j = 0; j <= l2; j++) { dp[i][j] = i + j; } } for (int i = 0; i < l1; i++) { for (int j = 0; j < l2; j++) { if (word1[i] == word2[j]) { dp[i + 1][j + 1] = dp[i][j]; } else { dp[i + 1][j + 1] = min({dp[i + 1][j + 1], dp[i][j] + 2, dp[i][j + 1] + 1, dp[i + 1][j] + 1}); } } } return dp[l1][l2]; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:stm8s系列编程
下一篇:LeetCode-643. Maximum Average Subarray I
相关文章

 发表评论

暂时没有评论,来抢沙发吧~