/** 72. Edit Distance * 12.10 by Mingyang * Dp[i][j] represents the minimum number of steps from the word1 before I convert to Word2 before the first J characters. * Suppose Word1 now traverses the character X,word2 traversal to the character Y (Word1 is currently traversing to a length of I,word2 to J). The following two possibilities: 1. * X==y, then do not have to do any editing operations, so dp[i][j] = dp[i-1][j-1] * 2. X! = y * (1) Insert Y in word1, then dp[i][j] = dp[i][j-1] + 1 * (2) in word1 delete x, then dp[i][j] = Dp[i-1][j] + 1 * (3) put Word1 X is replaced with Y, then dp[i][j] = dp[i-1][j-1] + 1 The least step is to take the minimum value of the three. * A little summary about DP, be sure to set the number of len+1, because dp[0][0] no meaning, the last is to ask for DP[LEN1][LEN2] * Then remember, a string of 0 when the other is all I*/ Public Static intmindistance (String word1, String word2) {intLen1 =word1.length (); intLen2 =word2.length (); //len1+1, len2+1, because finally return DP[LEN1][LEN2] int[] DP =New int[Len1 + 1] [Len2 + 1]; for(inti = 0; I <= len1; i++) dp[i][0] =i; for(intj = 0; J <= Len2; J + +) dp[0][J] =J; //iterate though, and check last char for(inti = 1; I <= len1; i++) { CharC1 = Word1.charat (i-1); for(intj = 1; J <= Len2; J + +) { CharC2 = Word2.charat (j-1); //if last chars equal if(C1 = =C2) { //Update DP value for +1 lengthDP[I][J] = dp[i-1][j-1]; } Else { intReplace = Dp[i-1][j-1] + 1; intInsert = Dp[i-1][j] + 1; intDelete = Dp[i][j-1] + 1; intMin =math.min (replace, insert); Min=math.min (min, delete); DP[I][J]=min; } } } returnDp[len1][len2]; }
Distance. Edit