zoukankan      html  css  js  c++  java
  • 0583. Delete Operation for Two Strings (M)

    Delete Operation for Two Strings (M)

    题目

    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.

    Example 1:

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

    Example 2:

    Input: word1 = "leetcode", word2 = "etco"
    Output: 4
    

    Constraints:

    • 1 <= word1.length, word2.length <= 500
    • word1 and word2 consist of only lowercase English letters.

    题意

    给定两个字符串,每次能从任一个字符串中删去一个字符,问最少经过多少次操作能使两个字符串相等。

    思路

    经典动态规划问题“两个字符串的编辑距离”的变种。dp[x][y]表示使s1中的前x个字符组成的子串s1(x)与s2中的前y个字符组成的子串s2(y)相等所需要的最小步数,那么有三种情况:(1) dp[x][y] = dp[x][y-1] + 1,删去s2的最后一个字符,只要求使s1(x)和s2(y-1)相等所需的步数;(2) dp[x][y] = dp[x-1][y] + 1,删去s1的最后一个字符,只要求使s1(x-1)和s2(y)相等所需的步数;(3) dp[x][y] = dp[x-1][y-1] + 0/2,如果最后一个字符相同,则只需求使s1(x-1)和s2(y-1)相等的步数,如果不相同,则先删去各自最后一个字符,再求步数。


    代码实现

    Java

    class Solution {
        public int minDistance(String word1, String word2) {
            int[][] dp = new int[word1.length() + 1][word2.length() + 1];
    
            for (int i = 0; i <= word1.length(); i++) {
                for (int j = 0; j <= word2.length(); j++) {
                    dp[i][j] = Integer.MAX_VALUE;
                    if (i == 0 || j == 0) {
                        dp[i][j] = i == 0 ? j : i;
                    } else {
                        dp[i][j] = Math.min(dp[i][j], dp[i-1][j] + 1);
                        dp[i][j] = Math.min(dp[i][j], dp[i][j-1] + 1);
                        dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + (word1.charAt(i - 1) == word2.charAt(j - 1) ? 0 : 2));
                    }
                }
            }
    
            return dp[word1.length()][word2.length()];
        }
    }
    
  • 相关阅读:
    [原创]启发式测试策略模型
    [原创]SSH框架介绍
    [原创]Sniffer工具培训
    [原创]浅谈Devops理念
    [原创接口测试技术介绍
    一个让我看了之后,痛哭不止的舞蹈!寻找有同感的人!
    多一点宽容,少一点抱怨;多一点付出,少一点指责。
    笼屉与夹肉馍(的制作方法) 之于 三层与MVC
    找工作、跳槽之旅——前言
    【自然框架.视频】基础设置(一)如何下载自然框架
  • 原文地址:https://www.cnblogs.com/mapoos/p/14741326.html
Copyright © 2011-2022 走看看