删除两个字符串的字符使它们相等
583. Delete Operation for Two Strings (Medium)
Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
题目描述:
有两个字符串,删除两个字符串中的字母,使得两个字符串相等,求问要删除几个字母?
思路分析:
可以将该题转化成求解两个字符串的最长公共子序列问题。
代码:
class Solution {
public int minDistance(String word1,String word2){
int m=word1.length();
int n=word2.length();
int [][]dp=new int [m+1][n+1]; //dp[i][j],表示word1的前i个字符和word2的前j个字符的最长公共子序列
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]);
}
}
}
return m+n-2*dp[m][n];
}
}