xinyu04

导航

LeetCode 583 Delete Operation for Two Strings

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

Solution

每一步删去其中一个字符串的一个字母,问最少的步数使得两个字符串相同。

显然经过最少删除步数以后,剩下的就是最长公共子序列。所以就转换成先求出最长公共子序列的长度 \(dp[n][m]\),然后 \(n-dp[n][m]+m-dp[n][m]\) 即可

点击查看代码
class Solution {
private:
    int dp[501][501];
public:
    int minDistance(string word1, string word2) {
        int n = word1.size(), m = word2.size();
        for(int i=0;i<=n;i++){
            for(int j=0;j<=m;j++){
                if(i==0||j==0)dp[i][j]=0;
                else dp[i][j]=INT_MIN;
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;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], max(dp[i-1][j], dp[i][j-1]));
                }
            }
        }
        return n-dp[n][m]+m-dp[n][m];
        
    }
};

posted on 2022-08-13 22:58  Blackzxy  阅读(11)  评论(0编辑  收藏  举报