LeetCode583_两个字符串的删除操作

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

LeetCode通道

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

示例:

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

提示:

  1. 给定单词的长度不超过500。
  2. 给定单词中的字符只含有小写字母。

题解:

class Solution {
     
    public int minDistance(String word1, String word2) {
     
        //分别获取word1和word2的长度为m,n
        int m = word1.length();
        int n = word2.length();
        //定义一个dp数组:其中dp[i][j]即为word1到达第i个位置,word2到达第j个位置时,最长公共子串的长度
        int[][] dp = new int[m + 1][n + 1];
        //因为我们定义的是dp[m + 1][n + 1],则直接[1,1]开始进行更新
        for(int i = 1; i <= m; i++) {
     
            for(int j = 1; j <= n; j++) {
     
                if(word1.charAt(i - 1) == word2.charAt(j - 1)) {
     
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }else {
     
                    dp[i][j] = Math.max(dp[i - 1][j],dp[i][j - 1]);
                }
            }
        }
        //题设要求我们返回最少需要的步数,其实我们只要求出最长公共子串的长度,即结果集为m + n - 2 * 最长公共子串的长度
        return m + n - 2 * dp[m][n];

    }
}

你可能感兴趣的:(LeetCode每日一题,动态规划,算法)