The minimal editing distance is a classic problem. This year, Microsoft intern's written examination has an extended version that involves templates and so on. At that time, a line of code was not written ..
Dp can solve this problem elegantly, and the state transition equation is also very clear. Pos [I] [j] indicates the editing distance between the first I characters of word1 and the first j characters of word2. If the word [I-1] is equal to the word [J-1], the pos [I] [j] is equal to the pos [I-1] [J-1]; otherwise, depending on the several actions edited, you can select one of the three cases with the lowest cost, and delete one character from word1? Delete a character from word2? Modify one of them? The boundary is also very simple. When the length of a string is 0, the editing distance must be based on the length of another string.
Code writing:
class Solution {public: int minDistance(string word1, string word2) { int len1 = word1.length(), len2 = word2.length(); int pos[len1+1][len2+1]; for(int i=0;i<=len1;i++) pos[i][0] = i; for(int i=0;i<=len2;i++) pos[0][i] = i; for(int i=1;i<=len1;i++){ for(int j=1;j<=len2;j++){ if(word1[i-1] == word2[j-1]) pos[i][j] = pos[i-1][j-1]; else{ pos[i][j] = min(pos[i-1][j], min(pos[i-1][j-1], pos[i][j-1]))+1; } } } return pos[len1][len2]; }};