583. Delete Operation for Two Strings
Posted andywu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了583. Delete Operation for Two Strings相关的知识,希望对你有一定的参考价值。
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:
- The length of given words won‘t exceed 500.
- 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的主要内容,如果未能解决你的问题,请参考以下文章
583. Delete Operation for Two Strings
583. Delete Operation for Two Strings
[leetcode-583-Delete Operation for Two Strings]
[LeetCode] 583. Delete Operation for Two Strings