Leetcode edit distance

Source: Internet
Author: User

Given two wordsWord1AndWord2, Find the minimum number of steps required to convertWord1ToWord2. (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

Enter word1 and word2 to find the minimum steps for converting from word1 to word2. One step for each conversion operation. The conversion operation is limited:

  • Delete a character
  • Insert a character
  • Replace one character

This question is solved using dynamic planning

Set the decision variable DP [I] [J] to represent the minimal step from word [0 .. I-1] To word2 [0 .. J-1]

See http://web.stanford.edu/class/cs124/lec/med.pdf

class Solution {public:    int minDistance(string word1, string word2) {        int len1 =word1.length(), len2 = word2.length();        if(len1 == 0) return len2;        if(len2 == 0) return len1;        if(word1 == word2) return 0;        vector<vector<int> > dp(len1+1, vector<int>(len2+1,0));        for(int i = 0; i <= len1; ++ i) dp[i][0] = i;        for(int j = 0; j <= len2; ++ j) dp[0][j] = j;        for(int i =1; i <= len1; ++ i){            for(int j = 1; j <= len2; ++ j){                dp[i][j] = min(dp[i-1][j-1]+(word1[i-1] != word2[j-1]? 1: 0),min(dp[i-1][j]+1, dp[i][j-1]+1));            }        }        return dp[len1][len2];    }};

 

 

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.