LeetCode Q 583 - Delete Operation for Two Strings
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.
Example 1: Input: "sea", "eat" ; Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.
Note:
- The length of given words won’t exceed 500.
- Characters in given words can only be lower-case letters.
Solution :
- State:
dp[i][j]
denotes the minimum number of steps to makeword1.substring(0, i+1)
andword2.substring(0, j+1)
the same; - state transfer function:
if (word1.charAt(i) == word2.charAt(j))
, we don’t need to do anying thereforedp[i][j] = dp[i-1][j-1]
- else
dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j]) + 1
, that is we can either delete char i from word1 or char j from word2.
- boundary case:
dp[0][j] = j, j = 0, 1, 2,... dp[i][0] = i, i = 0, 1, 2,...
Previously, I only set dp[0][1] = dp[1][0] = 1, so I made mistake!
Time Complexity: O(n * m)
Space Complexity: O(n * m)
Code:
public int minDistance(String word1, String word2) {
if (word1.length() == 0) return word2.length();
if (word2.length() == 0) return word1.length();
int[][] dp = new int[word1.length() + 1][word2.length() + 1];
for (int i = 0; i <= word1.length(); i++)
dp[i][0] = i;
for (int j = 0; j <= word2.length(); j++)
dp[0][j] = j;
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];
else
dp[i + 1][j + 1] = Math.min(dp[i + 1][j], dp[i][j + 1]) + 1;
}
}
return dp[word1.length()][word2.length()];
}