ID | Title | Difficulty | |
---|---|---|---|
Loading... |
583. Delete Operation for Two Strings
Medium
LeetCode
String, Dynamic Programming
Problem
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.
Code
712. Minimum ASCII Delete Sum for Two Strings
word1: leetcode
word2: etco
e t c o
[0,1,2,3,4]
l [1,2,3,4,5]
e [2,1,2,3,4]
e [3,2,3,4,5]
t [4,3,2,3,4]
c [5,4,3,2,3]
o [6,5,4,3,2]
d [7,6,5,4,3]
e [8,7,6,5,4]
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];
for(int j = 1; j <= len2; j++){
dp[0][j] = j;
}
for(int i = 1; i <= len1; i++){
dp[i][0] = i;
}
for(int i = 1; i <= len1; i++){
for(int j = 1; j <= len2; j++){
char c1 = word1.charAt(i - 1);
char c2 = word2.charAt(j - 1);
if(c1 == c2){
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1;
}
}
}
return dp[len1][len2];
}
}
按 <- 键看上一题!
582. Kill Process
按 -> 键看下一题!
584. Find Customer Referee