Explanation
We begin by initializing a array, where is the minimum number of edits to convert the first characters of the first string, which we denote as , into the first characters of the second string, which we denote as . The base cases in the array occur when one of the prefixes is empty.
This means we initialize the array as follows. Initialize where is the length of the prefix in , to be because it takes a minimum of deletions to convert the first characters into the first characters of (an empty string). Similarly, initialize where is the length of the prefix in , to be because it takes insertions to convert the first characters of (also an empty string) into the first characters of .
Now that we have initialized our array, we can move onto the transition. The options we have are to delete, insert, or replace a character from , or do nothing if the current characters are already equal.
When we delete a character, we convert into , and then delete . Therefore, this means that, if the last operation is a deletion, is equal to , where the extra is the cost of the delete operation.
When we insert a character, we effectively convert into , and then insert . So, is equal to , where the extra is the cost of the insert operation.
Finally, when we replace a character, we essentially convert into , then handle the last character. If and are different, then that counts as a replacement operation. So, the replacement operation can be represented compactly as
where is only when we actually need to replace the letter.
Combining the transition for each operation, the minimum number of edits required to convert the first characters in into the first characters of is
Using this transition, since each state depends only on the cell above, the cell to the left, and the diagonal upper-left cell, we fill the table from top to bottom and left to right. Our final answer is
Implementation
Time Complexity:
str1 = input()str2 = input()"""dp[i][j] is the minimum number of moves to change the first i lettersof the string into the first j letters of result."""dp = [[0] * (len(str2) + 1) for _ in range(len(str1) + 1)]# i edits needed to convert first i chars of string 1 into empty string
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!