Leetcode:edit Distance (string edit distance DP)

Source: Internet
Author: User

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

Idea: Test instructions to find the minimum editing distance for a string. F[I][J], representing the minimum editing distance between A[0][i] b[0][j].

FOREXAMPLR:STR1C str2d

1, C==d F[i][j]=f[i-1][j-1]
2, C!=d
(1) If C is changed to D then f[i][j]=f[i-1][j-1]+1
(2) If you add a D f[i][j]=f[i][j-1]+1 after C
(3) If C is removed f[i][j]=f[i-1][j-1]+1
The simple equation of state is
1,  1)}
1 classSolution {2  Public:3     intMindistance (stringWord1,stringWord2) {4         5         Const intn=word1.size ();6         Const intm=word2.size ();7         8vector<vector<int>> F (n+1,vector<int> (m+1,0));9         Ten          for(intI=0; i<=n;i++) Onef[i][0]=i; A              -          for(intj=0; j<=m;j++) -f[0][j]=J; the              -          for(intI=1; i<=n;i++) -              for(intj=1; j<=m;j++) -                 if(word1[i-1]==word2[j-1]) +f[i][j]=f[i-1][j-1]; -                 Else{ +F[i][j]=min (f[i-1][j-1],min (f[i-1][j],f[i][j-1]))+1; A                      at                 } -      -         returnF[n][m]; -     } -};

Leetcode:edit Distance (string edit distance DP)

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.