583. Delete Operation for Two Strings

https://leetcode.com/problems/delete-operation-for-two-strings/description/

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

 

Example 1:

Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Example 2:

Input: word1 = "leetcode", word2 = "etco"
Output: 4

 

Constraints:

  • 1 <= word1.length, word2.length <= 500
  • word1 and word2 consist of only lowercase English letters.
---
Time - O(M * N)
Space - O(M * N)
---

----
class Solution {
public int minDistance(String word1, String word2) {
if (word1.equals(word2)) {
return 0;
}
Integer[][] memo = new Integer[word1.length() + 1][word2.length() + 1];
return dfs(word1, 0, word2, 0, memo);
}
private int dfs(String word1, int i, String word2, int j, Integer[][] memo) {
if (memo[i][j] != null) {
return memo[i][j];
}
// remaining characters from word2
if (i == word1.length()) {
return word2.length() - j;
}
// remaining characters from word2
if (j == word2.length()) {
return word1.length() - i;
}
int ans = 0;
if (word1.charAt(i) == word2.charAt(j)) {
ans = dfs(word1, i + 1, word2, j + 1, memo);
} else {
// delete 1 char from word1 or word2
ans = 1 + Math.min(dfs(word1, i + 1, word2, j, memo), dfs(word1, i, word2, j + 1, memo));
}
memo[i][j] = ans;
return ans;
}
}
class Solution {
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 (i == 0 || j == 0) {
dp[i][j] = i + j;
continue;
}
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
// same char, so no change
dp[i][j] = dp[i - 1][j - 1];
} else {
// 1 (current diff char) + shortest path before
dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[word1.length()][word2.length()];
}
}
----