Original question stamp me
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:a) Insert a characterb) Delete a characterc) Replace a character
Resolution:
Typical dynamic planning questions.
Set distance [I, j] to indicate the editing distance between word1 [I] And word2 [J ].
1. When word1 [I] = word2 [J], distance [I, j] = distance [I-1, J-1]
2. When word1 [I] is not equal to word2 [J], three operations are involved:
Word1 inserts one character, that is, distance [I, j] = distance [I, j-1] + 1word1 deletes one character, that is, distance [I, j] = distance [I-1, J] + 1word1 replace 1 character, that is, distance [I, j] = distance [I-1, J-1] + 1
class Solution {public: int minDistance(string word1, string word2) { if (word1.size() == 0) return word2.size(); if (word2.size() == 0) return word1.size(); int rowNum = word1.size() + 1; int colNum = word2.size() + 1; std::vector<std::vector<int>> distance(rowNum, std::vector<int>(colNum, 0)); for (int i = 0; i < rowNum; ++i) { distance.at(i).at(0) = i; } for (int j = 0; j < colNum; ++j) { distance.at(0).at(j) = j; } for (int i = 1; i < rowNum; ++i) { for (int j = 1; j < colNum; ++j) { if (word1.at(i - 1) == word2.at(j - 1)) { distance.at(i).at(j) = distance.at(i - 1).at(j - 1); } else { int deleteCost = distance.at(i - 1).at(j) + 1; int insertCost = distance.at(i).at(j - 1) + 1; int replaceCost = distance.at(i - 1).at(j - 1) + 1; distance.at(i).at(j) = std::min(deleteCost, std::min(insertCost, replaceCost)); } } } return distance.at(word1.size()).at(word2.size()); }};
Note:
Set the distance two-dimensional matrix. The row and column are both corresponding to the string length plus 1.
Initialization of 0 rows and 0 columns of the distance two-dimensional matrix, Boundary Condition
Leetcode: edit distance string editing distance