One, dynamic programming algorithm
Dynamic programming algorithms are usually based on a recursive formula and one or more initial states. The solution of the current problem will be introduced by the solution of the last sub-problem. The use of dynamic programming to solve problems requires only polynomial complexity, so it is more than
Backtracking, violence laws are fast. First, we need to find the optimal solution of a state and then, with its help, find the optimal solution for the next state. To do is to abstract the state of dynamic programming and state transition equation (recursive formula).
Second, the editing distance
1, problem description
Set A and B are 2 strings. To convert string A to string B with a minimum of character manipulation. The character operations described here include:
(1) Delete a character;
(2) inserting a character;
(3) Change one character to another character.
The minimum character operand used to transform string A into string B is called the editing distance of the string A through B, which is recorded as D (A, A, a). Try to design an effective algorithm for the given 2 strings A and B, to calculate their editing distance d (A, a, a, a,).
Requirements:
Input: Line 1th is string A, line 2nd is string B.
Output: Edit distance D (A, b) for strings A
2. Solving process
A[1.....I] to B[1.....J] in d[i,j], then
D[i,0]=i: Represents the length of the string A to an empty string of the editing distance, that is, the lengths of the string A;
D[0,j]=j: Represents an empty string to a length of J of String B's editing distance, that is, the length of the string B;
D[I,J]=D[I-1,J-1]: if A[I]==B[J];
D[i,j]=min (D[i-1,j-1] (replace a[i] with B[j]), D[i-1,j] (A[i] delete), d[i,j-1] (insert A[i after b[j]))) +1:if a[i]! = B[j].
Java code:
public class Editdistance {
int min (int a,int b,int c) {
int t = a < b? A:B;
Return T < c? T:C;
}
void Editdistance (char[] s1,char[] s2) {
int len1=s1.length;
int len2=s2.length;
int d[][]=new int[len1+1][len2+1];
int i,j;
for (i = 0;i <= len1;i++)
D[i][0] = i;
for (j = 0;j <= len2;j++)
D[0][J] = j;
for (i = 1;i <= len1;i++)
for (j = 1;j <= len2;j++)
{
int cost = s1[i-1] = = S2[j-1]? 0:1;
int deletion = D[i-1][j] + 1;
int insertion = d[i][j-1] + 1;
int substitution = d[i-1][j-1] + cost;
D[i][j] = min (deletion,insertion,substitution);
}
System.out.println (D[len1][len2]);
}
public static void Main (string[] args)
{
Editdistance ed = new Editdistance ();
String a= "Abd";
String b= "BCD";
Ed.editdistance (A.tochararray (), B.tochararray ());
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Dynamic programming solving editing distances