583. 两个字符串的删除操作

 

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

 

示例:

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

 

 

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:

        n1 = len(word1)
        n2 = len(word2) 
        dp = [[0]*(n2+1) for _ in range(n1+1)]

        for i in range(n1+1):
            dp[i][0] = i
        for j in range(n2+1):
            dp[0][j] = j

        for i in range(1,n1+1):
            for j in range(1,n2+1):
                if word1[i-1]!=word2[j-1]:
                    dp[i][j] = min(dp[i][j-1],dp[i-1][j]) + 1
                else:
                    dp[i][j] = dp[i-1][j-1]
        return dp[n1][n2]

 

 

 

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        n1 = len(word1)
        n2 = len(word2)
        dp = [[0]*(n2+1) for _ in range(n1+1)]

        for i in range(n1+1):
            dp[i][0] = i
        for j in range(n2+1):
            dp[0][j] = j

        for i in range(1,n1+1):
            for j in range(1,n2+1):
                if word1[i-1] == word2[j-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i-1][j],dp[i][j-1])+1
        return dp[n1][n2]

 

 

 

/*
 * @lc app=leetcode.cn id=583 lang=cpp
 *
 * [583] 两个字符串的删除操作
 */

// @lc code=start
class Solution {
public:
    int minDistance(string word1, string word2) {
        int n1 = word1.size();
        int n2 = word2.size();
        vector<vector<int>> dp = vector<vector<int>>(n1+1,vector<int>(n2+1,0));
        for(int i = 1; i <= n1 ;i++){
            for(int j = 1; j <= n2; j++) {
                if(word1[i-1]==word2[j-1]) {
                    dp[i][j] = 1 + dp[i-1][j-1];
                } else {
                    dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
                }
            }
        }
        int lcs = dp[n1][n2];
        return n1-lcs + n2-lcs;
    }
};
// @lc code=end

 

 

posted @ 2021-09-16 23:31  乐乐章  阅读(57)  评论(0编辑  收藏  举报