[LeetCode] 583. Delete Operation for Two Strings

题:https://leetcode.com/problems/delete-operation-for-two-strings/description/

题目

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: 2

Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.
Note:

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

题目大意

删除两个字符串的字符使它们相等,求最小的删除数。

思路

转换为
求两个字符串的最长公共子序列问题

动态规划求解,这样的考虑很明显 因为 对于str1[0:p] 与 str2[0:k] 若 已经求得最长子序列,那么 str1 与 str2 可从局部的解中获得全局优解。

dp[i][j]状态表示:S1 的前 i 个字符与 S2 的前 j 个字符最长公共子序列的长度。

状态转移:

根据 S1i 与 S2j 值是否相等,分为两种情况:

  • 当 S1i==S2j 时,那么就能在 S1 的前 i-1 个字符与 S2 的前 j-1 个字符最长公共子序列的基础上再加上 S1i 这个值,最长公共子序列长度加 1,即 dp[i][j] = dp[i-1][j-1] + 1。
  • 当 S1i != S2j 时,此时最长公共子序列为 S1 的前 i-1 个字符和 S2 的前 j 个字符最长公共子序列,或者 S1 的前 i 个字符和 S2 的前 j-1 个字符最长公共子序列,取它们的最大者,即 dp[i][j] = max{ dp[i-1][j], dp[i][j-1] }。

状态转移方程:

	if(S1<sub>i</sub>==S2<sub>j</sub>)
	    dp[i][j] = dp[i-1][j-1]+1;
	else
	    dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);

最后需要变化的 字符数为 n+m-2*dp[n][m]。

code:

class Solution {
    public int minDistance(String word1, String word2) {
        int n = word1.length(),m = word2.length();
        int [][] dp = new int[n+1][m+1];
        for(int i = 1;i < n+1;i++)
            for(int j = 1; j < m+1 ;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]);
            }
        return n+m-2*dp[n][m];
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83059401