原題連接在這裏:https://leetcode.com/problems/delete-operation-for-two-strings/description/html
題目:數組
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.post
Example 1:ui
Input: "sea", "eat" Output: 2 Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
Note:url
題解:spa
找LCS的長度n. word1.length()+word2.length()-2*n. 就是答案.code
用DP找LCS的長度. 須要儲存的歷史信息是到當前點的LCS長度. 用dp[i][j]儲存, 表示word1到i和word2到j的LCS長度.htm
遞推時, 如果當前字符match, 在dp[i-1][j-1]的基礎上加1便可.blog
若不match, 取dp[i][j-1] 和 dp[i-1][j]中較大值便可.ip
初始化都是0.
Time Complexity: O(m*n). m = word1.length(), n = word2.length().
Space: O(m*n).
AC Java:
1 class Solution { 2 public int minDistance(String word1, String word2) { 3 int len1 = word1.length(); 4 int len2 = word2.length(); 5 int [][] dp = new int[len1+1][len2+1]; 6 for(int i = 0; i<=len1; i++){ 7 for(int j = 0; j<=len2; j++){ 8 if(i==0 || j==0){ 9 continue; 10 }else if(word1.charAt(i-1) == word2.charAt(j-1)){ 11 dp[i][j] = 1 + dp[i-1][j-1]; 12 }else{ 13 dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); 14 } 15 } 16 } 17 return len1+len2-2*dp[len1][len2]; 18 } 19 }
或者像Edit Distance直接計算須要最小的operations數目.
DP問題. 須要儲存的歷史信息是各自到當前的位置變成相同string須要的最小operation數目. 用二維數組來出巡.
遞推時, 如果當前字符match, 不須要額外操做. dp[i][j] = dp[i-1][j-1].
若不match, 須要在dp[i-1][j], dp[i][j-1]中取較小值加1.
初始化或一邊在初始位置沒動, 最小operation數目就是另外一邊的位置所有減掉.
答案dp[m][n]. m = word1.length(). n = word2.length().
Time Complexity: O(m*n).
Space: O(m*n).
AC Java:
1 class Solution { 2 public int minDistance(String word1, String word2) { 3 int m = word1.length(); 4 int n = word2.length(); 5 int [][] dp = new int[m+1][n+1]; 6 for(int i = 0; i<=m; i++){ 7 for(int j = 0; j<=n; j++){ 8 if(i == 0 || j == 0){ 9 dp[i][j] = i+j; 10 }else if(word1.charAt(i-1) == word2.charAt(j-1)){ 11 dp[i][j] = dp[i-1][j-1]; 12 }else{ 13 dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + 1; 14 } 15 } 16 } 17 return dp[m][n]; 18 } 19 }
也能夠降維節省空間.
Time Complexity: O(m*n).
Space: O(n).
AC Java:
1 class Solution { 2 public int minDistance(String word1, String word2) { 3 int m = word1.length(); 4 int n = word2.length(); 5 int [] dp = new int[n+1]; 6 for(int i = 0; i<=m; i++){ 7 int [] temp = new int[n+1]; 8 for(int j = 0; j<=n; j++){ 9 if(i == 0 || j == 0){ 10 temp[j] = i+j; 11 }else if(word1.charAt(i-1) == word2.charAt(j-1)){ 12 temp[j] = dp[j-1]; 13 }else{ 14 temp[j] = Math.min(dp[j], temp[j-1]) + 1; 15 } 16 } 17 dp = temp; 18 } 19 return dp[n]; 20 } 21 }
相似Longest Common Subsequence, Minimum ASCII Delete Sum for Two Strings, Edit Distance.