Distance. Edit

Source: Internet
Author: User

    /** 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.