Levenshein distance, the Chinese name is the minimum editing distance, which aims to find the number of characters to be changed between two strings and then become consistent. The algorithm uses a dynamic programming algorithm. This problem has the optimal sub-structure. The minimum editing distance includes the minimum editing distance of the sub-part. The following formula is provided.
Where d [I-1, J] + 1 represents string S2 insert a letter, d [I, J-1] + 1 represents string S1 delete a letter, then when xi = YJ, no cost, so the price is the same as the price of the previous d [I-1, J-1]; otherwise + 1, then d [I, j] is the smallest of the above three.
Algorithm Implementation (Python ):
Assume that the two strings are S1 and S2, and their lengths are M and N. First, apply for a matrix (m + 1) * (n + 1, initialize the first row and the first column, d [I, 0] = I, d [0, J] = J, and then find other elements in the matrix according to the formula, the editing distance between two strings is the value of d [n, m]. The Code is as follows:
#!/usr/bin/env python# -*- coding: utf-8 -*-__author__ = 'xanxus's1, s2 = raw_input('String 1:'), raw_input('String 2:')m, n = len(s1), len(s2)colsize, matrix = m + 1, []for i in range((m + 1) * (n + 1)): matrix.append(0)for i in range(colsize): matrix[i] = ifor i in range(n + 1): matrix[i * colsize] = ifor i in range(n + 1)[1:n + 1]: for j in range(m + 1)[1:m + 1]: cost = 0 if s1[j - 1] == s2[i - 1]: cost = 0 else: cost = 1 minValue = matrix[(i - 1) * colsize + j] + 1 if minValue > matrix[i * colsize + j - 1] + 1: minValue = matrix[i * colsize + j - 1] + 1 if minValue > matrix[(i - 1) * colsize + j - 1] + cost: minValue = matrix[(i - 1) * colsize + j - 1] + cost matrix[i * colsize + j] = minValueprint matrix[n * colsize + m]