Leetcode------Edit Distance

Source: Internet
Author: User

Title: Edit Distance
Pass Rate: 26.1%
Difficulty: Difficult

Given 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

The topic is the classic problem of dynamic programming, the formula is as follows:

1, S1.length==0,return s2.length;

2, S2.length==0,return s1.length;

3. If S1.charat (i) ==s2.charat (j), Res[i][j]=res[i-1][j-1]

else Res[i][j]=min (res[i-1][j],res[i][j-1],res[i-1][i-1]+1)

See the code specifically:

1  Public classSolution {2      Public intmindistance (String word1, String word2) {3 intLen1 =word1.length ();4     intLen2 =word2.length ();5  6     //len1+1, len2+1, because finally return DP[LEN1][LEN2]7     int[] DP =New int[Len1 + 1] [Len2 + 1];8  9      for(inti = 0; I <= len1; i++) TenDp[i][0] =i; One      A      for(intj = 0; J <= Len2; J + +)  -DP[0][J] =J; -      the   -     //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); +   A             //if last chars equal at             if(C1 = =C2) { -                 //Update DP value for +1 length -DP[I][J] = dp[i-1][j-1]; -}Else { -                 intReplace = Dp[i-1][j-1] + 1; -                 intInsert = Dp[i-1][j] + 1; in                 intDelete = Dp[i][j-1] + 1; -   to                 intMin =math.min (replace, insert); +Min =math.min (min,delete); -DP[I][J] =min; the             } *         } $     }Panax Notoginseng   -     returnDp[len1][len2]; the     } +}

     

Leetcode------Edit Distance

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.