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]; }};