그들이 동일 있도록 문자의 두 문자열을 제거
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];
}
}