Edit Distance
Given 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 character
b) Delete a character
c) Replace a character
Problem Solving Ideas:
This problem calculates the editing distance of two texts. With the idea of dynamic planning. D[I][J] Represents the minimum number of transitions from string A (0..I) to B (0...J). Then there are:
Class Solution {public: int mindistance (string word1, String word2) { int m = Word1.length (); int n = word2.length (); if (m = = 0 | | n = = 0) { return Max (M, n); } Vector<vector<int>> D (m + 1, vector<int> (n + 1, 0)); for (int i = 0; i<=n; i++) { d[0][i] = i; } for (int i=0; i<=m; i++) { d[i][0] = i; } for (int i = 1; i<=m; i++) {for (int j = 1; j<=n; j + +) { if (word1[i-1] = = Word2[j-1]) { D[i][j] = d[i-1][ J-1]; } else{ D[i][j] = min (min (d[i][j-1], d[i-1][j]), d[i-1][j-1]) + 1;}} } return d[m][n];} ;
The time complexity and space complexity of the above code are all O (n^2). You can change the code to the space complexity of O (n).
Class Solution {public: int mindistance (string word1, String word2) { int m = Word1.length (); int n = word2.length (); if (m = = 0 | | n = = 0) { return Max (M, n); } Vector<int> d (n + 1, 0); for (int i = 0; i<=n; i++) { d[i] = i; } for (int i = 1; i<=m; i++) { int left = i; int leftup = i-1; for (int j = 1; j<=n; j + +) { int up = d[j]; int newval; if (word1[i-1] = = Word2[j-1]) { newval = Leftup; } else{ newval = min (min (left, up), leftup) + 1; } Leftup = D[j]; D[J] = newval; left = D[j]; } } return d[n];} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Edit Distance