字符串编辑距离

 1 #include <iostream>
2 using namespace std;
3
4 #include <string.h>
5
6 #define N 100
7 int matrix[N][N];
8 int penalty = 10;
9
10 int MinOf3(int x, int y, int z) {
11 x = x < y ? x : y;
12 return x < z ? x : z;
13 }
14
15 int MinOf2(int x, int y)
16 {
17 return x < y ? x : y;
18 }
19 int Distance(const char * p1, const char * p2)
20 {
21 int l1 = strlen(p1);
22 int l2 = strlen(p2);
23 int i, j;
24 matrix[0][0] = 0;
25 for (i = 1; i <= l1; ++i) {
26 matrix[i][0] = i * penalty;
27 }
28 for (j = 1; j <= l2; ++j) {
29 matrix[0][j] = j * penalty;
30 }
31
32 for (i = 1; i <= l1; ++i) {
33 for (j = 1; j <= l2; ++j) {
34 if (p1[i - 1] == p2[j - 1]) {
35 matrix[i][j] = matrix[i - 1][j - 1];
36 } else {
37 matrix[i][j] = MinOf3(matrix[i - 1][j], matrix[i][j - 1],
38 matrix[i - 1][j - 1]) + penalty;
39 }
40 }
41 }
42
43 return matrix[l1][l2];
44 }
45
46 void Print(int n1, int n2)
47 {
48 int i, j;
49 for (i = 0; i <= n1; ++i) {
50 for (j = 0; j <= n2; ++j) {
51 printf("%3d", matrix[i][j]);
52 }
53 printf("\n");
54 }
55 }
56
57 int main()
58 {
59 cout << Distance("abc", "ab") << endl;
60 Print(3, 2);
61
62 return 0;
63 }

你可能感兴趣的:(字符串)