問題
給定兩個單詞word1和word2,找出使word1和word2相同所需的最小步驟數,在每個步驟中可以刪除任意字符串中的一個字符。
輸入: "sea", "eat"
輸出: 2
解釋: 你需要一步讓“sea”變成“ea”,另一步讓“eat”變成“ea”。
解析
乍一看看編輯距離差不多,其實最接近的是最長公共子序列問題。求得最長公共子序列之後,用原本字符串的長度之和減掉2個最長公共子序列的長度即爲最後的結果。
Java代碼
public int minDistance(String word1, String word2) {
int dp[][] = new int[word1.length()+1][word2.length()+1];
for(int i=0;i<word1.length();i++){
for(int j=0;j<word2.length();j++){
if(word1.charAt(i)==word2.charAt(j)){
dp[i+1][j+1] = dp[i][j]+1;
}
else{
dp[i+1][j+1] = Math.max(dp[i][j+1],dp[i+1][j]);
}
}
}
return word1.length()+word2.length()-2*dp[word1.length()][word2.length()];
}