码迷,mamicode.com
首页 > 其他好文 > 详细

583. Delete Operation for Two Strings

时间:2017-10-18 16:14:31      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:dia   exce   col   blog   other   否则   require   private   equals   

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.

题目含义:给定两个字符串,每次可以删除一个字母,求使得两个字符串相等的最小步骤

方法一:找到最终公共子串,然后计算其余字符长度

    private String findMaxCommonSubString(String word1,String word2)
    {
        String min = word1.length()<word2.length()?word1:word2;
        String max = min.equals(word1)?word2:word1;
        if (max.contains(min)) return min;

        for (int i=0;i<min.length();i++)
        {
            for (int a=0,b=min.length()-i;b!=min.length()+1;a++,b++)
            {
                String subStr = min.substring(a,b);
                if (max.contains(subStr)) return subStr;
            }
        }
        return "";
    }

    public int minDistance(String word1, String word2) {
        String maxCommonSubStr = findMaxCommonSubString(word1, word2);
        if (maxCommonSubStr.isEmpty()) return word1.length() + word2.length();
        int commonPosi1 = word1.indexOf(maxCommonSubStr);
        int commonPosi2 = word2.indexOf(maxCommonSubStr);
        return word1.length() - maxCommonSubStr.length() + word2.length() - maxCommonSubStr.length();           
            return word1.length() - val + word2.length() - val;
    }

方法二:问题可以转化为求两个字符串的最长公共子序列(注意不是子字符串)。

首先求最长公共子序列(LCS),然后,用两个字符串的长度分别减去公共子序列的长度,然后再相加即为要删除的长度。

设有二维数组技术分享表示技术分享技术分享位和技术分享技术分享位之前的最长公共子序列的长度,则有:

技术分享
技术分享

其中,技术分享技术分享的第技术分享位与技术分享的第技术分享位完全相同时为“1”,否则为“0”。

此时,技术分享中最大的数便是技术分享技术分享的最长公共子序列的长度,依据该数组回溯,便可找出最长公共子序列。

 1     public int minDistance(String word1, String word2) {
 2             int dp[][] = new int[word1.length()+1][word2.length()+1];
 3             for(int i = 0; i <= word1.length(); i++) {
 4                 for(int j = 0; j <= word2.length(); j++) {
 5                     if(i == 0 || j == 0) dp[i][j] = 0;
 6                     else dp[i][j] = (word1.charAt(i-1) == word2.charAt(j-1)) ? dp[i-1][j-1] + 1
 7                             : Math.max(dp[i-1][j], dp[i][j-1]);
 8                 }
 9             }
10             int val =  dp[word1.length()][word2.length()];
11             return word1.length() - val + word2.length() - val;
12     }

 

583. Delete Operation for Two Strings

标签:dia   exce   col   blog   other   否则   require   private   equals   

原文地址:http://www.cnblogs.com/wzj4858/p/7686936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!