Leetcode Note: Edit Distance
I. Description
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:
Insert a character
Delete a character
Replace a character
Ii. Question Analysis
Given the two strings word1 and word2, calculate the minimum number of edits required to convert word1 to word2. The following three types of editing operations are allowed:
Replace one character with another
Insert a character into the string
Deletes a character from a string.
For example, convert A (abc) to B (acbc ):
You can perform the following operations:
Acc (B → c) Replacement
Acb (c → B) Replacement
Acbc (→ c) insert
This is not the minimum number of edits, because you only need to delete the second character.cYou only need to perform the operation once.
UseiStringword1(Starting from subscript 1), usejStringword2. Usek[i][j]To indicateword1[1, ... , i]Toword2[1, ... , j]The minimum number of operations to edit. There are the following rules:
k[i][0] = i;k[0][j] = j;k[i][j] = k[i - 1][j - 1] (if word1[i] == word2[j])k[i][j] = min(k[i - 1][j - 1], k[i][j - 1], k[i - 1][j]) + 1 (if word1[i] != word2[j])
Iii. Sample Code
#include
#include
#include
using namespace std;class Solution{public: int minDistance(const string &word1, const string &word2) { const size_t m = word1.size() + 1; const size_t n = word2.size() + 1; vector
> k(m, vector
(n)); for (size_t i = 0; i < m; ++i) k[i][0] = i; for (size_t j = 0; j < n; ++j) k[0][j] = j; for (size_t i = 1; i < m; ++i) { for (size_t j = 1; j < n; ++j) { if (word1[i - 1] == word2[j - 1]) k[i][j] = k[i - 1][j - 1]; else k[i][j] = min(k[i - 1][j - 1], min(k[i - 1][j], k[i][j - 1])) + 1; } } return k[m - 1][n - 1]; }};
Iv. Summary
It is difficult to quickly write the state transition equation for a classic question of dynamic planning.