天天看點

232、兩個字元串的删除操作

題目描述:

給定兩個單詞 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步數,每步可以删除任意一個字元串中的一個字元。

示例 1:

輸入: “sea”, “eat”

輸出: 2

解釋: 第一步将"sea"變為"ea",第二步将"eat"變為"ea"

說明:

給定單詞的長度不超過500。

給定單詞中的字元隻含有小寫字母。

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/delete-operation-for-two-strings

著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

其實就是求兩個字元串的最長公共子串,然後拿兩個長度之和減去 最長公共子串* 2

代碼:

class Solution {
    public int minDistance(String word1, String word2) {
        	int len1 = word1.length();
		int len2 = word2.length();
		int dp[][] = new int[len1 + 1][len2 + 1];
		int max = 0;
		for (int i = 1; i < len1 + 1; i++) {
			for (int j = 1; j < len2 + 1; 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]);
				}
				max = Math.max(dp[i][j], max);
			}
		}
		return word1.length() + word2.length() - 2 * max;
    }
}
           

官方解釋使用動态規劃求解