Given two 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:
Given word1 = "mart"
and word2 = "karma"
, return 3
.
int minDistance(string word1, string word2) { vector<vector<int>> operates(word1.size()+1, vector<int>(word2.size()+1, 0)); for (int i = 0; i < operates.size(); i ++) { operates[i][0] = i; } for (int i = 1; i < operates[0].size(); i ++) { operates[0][i] = i; } for (int r = 1; r < operates.size(); r ++) { for (int c = 1; c < operates[0].size(); c ++) { int t = word1[r-1] == word2[c-1] ? 1 : 0; if (t) { operates[r][c] = operates[r-1][c-1]; } else { operates[r][c] = min(operates[r-1][c-1], min(operates[r-1][c], operates[r][c-1])) + 1; } } } return operates.back().back(); }
原文:http://www.cnblogs.com/whlsai/p/5152691.html