串的模式匹配算法 ------ KMP算法

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 int* get_next(char t[], int length)
 6 {
 7     int i = 0, j = -1;
 8     int* next = (int *)malloc(length * sizeof(int));
 9     next[0] = -1;
10     while (i < length)
11     {
12         if (j == -1 || t[i] == t[j])
13         {
14             i++;
15             j++;
16             next[i] = j;
17         }
18         else
19         {
20             j = next[j];
21         }
22     }
23 
24     return next;
25 }
26 
27 int  Index_KMP(char s[], char t[], int sl, int tl, int next[])
28 {
29     int j, i;
30     j = 0;
31     i = 0;
32     while (j < tl && i < sl)
33     {
34         if (j == -1 || s[i] == t[j])
35         {
36             i++;
37             j++;
38         }
39         else
40         {
41             j = next[j];
42         }
43     }
44     if (j == tl)
45     {
46         return i - tl;
47     }
48     else
49     {
50         return 0;
51     }
52 }
53 
54 
55 int main()
56 {
57 
58     char s[] = "acabaabaabcacaabc";
59     char t[] = "abaabcac";
60     int tl = strlen(t);
61     int sl = strlen(s);
62     int *next = get_next(t, tl);
63     int c = Index_KMP(s,t,sl,tl,next); //返回开始正确匹配的下标(s的下标)
64     printf("%d\n",c);
65     return 0;
66 }

理解:

模式匹配就是将主串中下标为i的元素与模式串中下标为j的元素进行比较(比较过程中i不会回溯 而j的值会按照next对应的值进行回溯)

猜你喜欢

转载自www.cnblogs.com/Ghost4C-QH/p/10363705.html