Remove two strings of characters so that they are equal
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".
Subject description:
There are two strings, remove the two strings of letters, making the two strings are equal, to inquire of you want to delete a few letters?
Analysis of ideas:
The problem can be converted into the problem solving the longest common subsequence of two strings.
Code:
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];
}
}