LeetCode -- Edit Distance
Description:
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step .)
You have the following 3 operations permitted on a word:
A) Insert a character
B) Delete a character
C) Replace a character
It is the minimum number of changes from word 1 (word1) to word 2 (word2). Each change can only be: add, delete, or update 1 character.
This is a typical DP question. recursive formula:
Assume that dp [I, j] represents the minimum number of changes in the I-1 characters before word1 to the first J-1 characters before word2.
Initialize dp first. When word1 is an empty string, dp [I, 0] Is I (in this case, only I characters can be added), where I, [0, n]. Similarly, the initialization of dp [0, I] can be considered as the case where word2 is an empty string and the number of characters from word1 to an empty string is also I (that is, only I characters can be removed ).
I. When word1 [I] And word2 [j] are equal, no update times are required, that is, dp [I + 1, j + 1] = dp [I, j]
II. When word1 [I] And word2 [j] are different, the current comparison may be divided into three possibilities:
1. word1 [I-1] And word2 [J-1] comparison
2. word1 [I] And word2 [J-1]
3. word [I-1] And word2 [j].
You only need to determine the minimum value from the dp array that stores the comparison results in these three cases.
That is,
Dp [I + 1, j + 1] = Minimum value (dp [I, j + 1], dp [I + 1, j], dp [I, j])
Implementation Code:
public class Solution { public int MinDistance(string word1, string word2) { var dp = new int [word1.Length+1, word2.Length+1]; for(var i = 0;i < word1.Length + 1; i++){ dp[i,0] = i; } for(var i = 0;i < word2.Length + 1; i++){ dp[0,i] = i; } for(var i = 0; i < word1.Length; i++){ for(var j = 0;j < word2.Length; j++){ if(word1[i] == word2[j]){ dp[i+1,j+1] = dp[i,j]; } else{ var min = Math.Min(Math.Min(dp[i,j], dp[i,j+1]), dp[i+1,j]); dp[i+1,j+1] = min + 1; } } } return dp[word1.Length, word2.Length]; }}