KMP

全部代码

  1 #include <stdio.h>
  2 #include <assert.h>
  3 #include <stdlib.h>
  4 #include <string.h>
  5 
  6 int *GetNext(const char *match)
  7 {
  8     int *pNext = NULL;
  9     int i;
 10     int j;
 11 
 12     assert(match!=NULL);
 13 
 14     pNext = (int *)malloc(strlen(match)*sizeof(int));
 15     if(NULL == pNext)
 16     {
 17         printf("pNext空间分配失败!\n");
 18         exit(-1);
 19     }
 20     i = 1;
 21     j = i-1;
 22     //起始位置
 23     pNext[0] = 0;
 24 
 25     while(i < strlen(match))
 26     {
 27         //当前字符与前面的next值所对应位置的值相等
 28         if(match[i] == match[pNext[j]])
 29         {
 30             pNext[i] = pNext[j]+1;
 31             ++i;
 32             j = i-1;
 33         }
 34         //前一个next值为0
 35         else if(0 == pNext[j])
 36         {
 37             pNext[i] = 0;
 38             ++i;
 39             j = i-1;
 40         }
 41         //不满足以上情况  向前跳转  再进行比较
 42         else
 43         {
 44             j = pNext[j] - 1;
 45         }
 46     }
 47 
 48     return pNext;
 49 }
 50 
 51 int KMP(const char *src, const char *match)
 52 {
 53     int i;
 54     int j;
 55     int *pNext = NULL;
 56 
 57     assert(src!=NULL && match!=NULL);
 58 
 59     pNext = GetNext(match);
 60     i = 0;
 61     j = 0;
 62 
 63     while(i<strlen(src) && j<strlen(match))
 64     {
 65         //相等  二者均向后移动
 66         if(src[i] == match[j])
 67         {
 68             ++i;
 69             ++j;
 70         }
 71         //不相等
 72         else
 73         {
 74             //匹配串已经回到起始位置 且仍不相等 主串向后移动
 75             if(0 == j)
 76             {
 77                 ++i;
 78             }
 79             //不满足上述情况  匹配串向前跳转
 80             else
 81             {
 82                 j = pNext[j-1];
 83             }
 84         }
 85     }
 86 
 87     if(0 == match[j])
 88     {
 89         return i - strlen(match);
 90     }
 91 
 92     return -1;
 93 }
 94 
 95 int main(void)
 96 {
 97     char *src = "ababcabcdef";
 98     char *match = "abc";
 99     printf("%d\n", KMP(src, match));
100 
101     return 0;
102 }

 

posted @ 2017-11-06 20:55  c&z  阅读(437)  评论(0编辑  收藏  举报