Simply put, the edit distance is the number of changes to one string modified into another. If the number of changes is smaller, we can simply assume that the relationship between the two strings is tighter. For example today is the day of the week for today is Friday and tomorrow is Friday comparison, with today is Friday more closely, because the former edit distance is 1, the latter's editing distance is 2.
More detailed Baidu Encyclopedia has been said very clearly, here no longer repeat, mainly give JavaScript implementation methods:
According to the natural language algorithm, we first need to create a two-dimensional table based on the length of two strings:
function Levenshtein (A, b) {
var al = a.length + 1;
var bl = b.length + 1;
var result = [];
var temp = 0;
Creates a two-dimensional array for
(var i = 0; i < al; Result[i] = [i++]) {} for
(var i = 0; i < bl; Result[0][i] = i++) {}
}
Then you need to traverse the two-bit array and get the minimum value of three values by following these rules:
If the topmost character equals the leftmost character, the upper-left digit. Otherwise, the upper left digit + 1.
Left-Hand digit + 1
Top number + 1
You need to determine whether two values are equal to determine whether the upper left number is + 1, so introduce the TEMP variable. We can write the following traversal code:
for (i = 1; i < Al; i++) {for
(var j = 1; j < BL; J +) {
//determine whether the top and left digits are equal
temp = a[i-1] = = B[j -1]? 0:1;
RESULT[I-1][J] + 1 left digit
//result[i][j-1] + 1 above number
//result[i-1][j-1] + temp upper left-hand digit
result[i] [j] = Math.min (Result[i-1][j] + 1, result[i][j-1] + 1, result[i-1][j-1] + temp);
}
}
Finally, the final value of the two-dimensional array is returned, which is the edit distance:
return result[i-1][j-1];
This function is complete:
Function levenshtein (a, b) { var al = a.length + 1;
var bl = b.length + 1;
var result = [];
var temp = 0; // create a two-dimensional array for (var i = 0; i < al; result[i] = [i++]) {} for (Var i = 0; i < bl; result[0][i] = i++) {} for (i = 1; i < al; i++) { for (var j = 1; j < bl; j++) { // determine whether the top and left digits are equal temp = a[i - 1] == b[j -
1] ? 0 : 1; // result[i - 1][j] + 1 left-hand digital // result[i Digital // r above][j - 1] + 1 esult[i - 1][j - 1] + temp Top left Digit result[i][j] = Math.min (result[i - 1][j] + 1, result[i][j - 1] + 1, result[
I&NBSP;-&NBSP;1][J&NBSP;-&NBSP;1]&NBSP;+&NBSP;TEMP);
} return result[i-1][j-1]; }
Practical application
So now we're going to implement a simple search function.
The general idea is that the data and to search for the string to calculate the editing distance, and then sorted, the edit distance of small placed on the above display. Specific Demo to do in
Take a look at a small written example