KMP算法源码实现

 1 #include <iostream>
 2 using namespace std;
 3 
 4 const int* get_substring_arr(const char* sequence);
 5 void kmp(const char* src, const char* substring, const int* a);
 6 
 7 int main()
 8 {
 9     char* src = "acabaabaabcacaabc";
10     char* substring = "abaabcac";
11     kmp(src, substring, get_substring_arr(substring));
12     return 0;
13 }
14 
15 //process the substring
16 const int* get_substring_arr(const char* substring)
17 {
18     int substring_len = strlen(substring);
19     int* a = new int[substring_len];
20     a[0] = -1;
21     int j = -1;
22     for(int i = 1; i < substring_len; i++)
23     {
24         while(j > -1 && substring[i] != substring[j + 1])
25             j = a[j];
26         if(substring[j+1] == substring[i])
27             j = j + 1;
28         a[i] = j;
29     }
30     return a;
31 }
32 
33 //process src & substring to get the position
34 void kmp(const char* src, const char* substring, const int* a)
35 {
36     int j = -1;
37     int substring_len = strlen(substring);
38     int src_len = strlen(src);
39     for(int i = 0; i < src_len; i++)
40     {
41         while(j > -1 && src[i] != substring[j + 1])
42             j = a[j];
43         if(src[i] == substring[j + 1])
44             j++;
45 
46         if(j == substring_len -1)
47         {
48             printf("From position %d to position %d\n", i + 2 - substring_len, i+1);
49             j = a[j];
50         }
51     }
52 }

 

posted @ 2015-04-02 12:26  poore  阅读(239)  评论(0)    收藏  举报