KMP算法源码

来源:互联网 发布:淘宝店卖保健品 编辑:程序博客网 时间:2024/05/18 18:01
 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4
  5 void getNextVal(char* T, int* nextVal);
  6 int IndexKMP(char* S, char* T);
  7 void getNextVal(char* T, int* nextVal)
  8 {
  9     int i = 1, j = 0;
 10     int nLen = strlen(T);
 11     printf("getNextVal-----nLen=%d\n", nLen);
 12     nextVal[0] = 0;
 13     while (i < nLen - 1)
 14     {
 15         if (T[i] == T[j])
 16         {
 17             ++i;
 18             ++j;
 19             if (T[i] != T[j])
 20             {
 21                 nextVal[i] = j;
 22             }
 23             else
 24             {
 25                 nextVal[i] = nextVal[j];
 26             }
 27         }
 28         else if (j == 0)
 29         {
 30             ++i;
 31             nextVal[i] = j;
 32         }
 33         else
 34         {
 35             j = nextVal[j];
 36         }
 37     }
 38 }
 39
 40 int IndexKMP(char* S, char* T)
 41 {
 42     int nLenT = strlen(T);
 43     int nLenS = strlen(S);
 44     int i = 0,j = 0;
 45     int* nextVal = (int*)malloc(sizeof(int) * nLenT);
 46     printf("IndexKMP----------nLenT=%d\n", nLenT);
 47     printf("IndexKMP----------nLenS=%d\n", nLenS);
 48     getNextVal(T, nextVal);
 49     
 50     while (i <= nLenS && j < nLenT)
 51     {
 52         if (S[i] == T[j])                                  
 53         {
 54             ++i;
 55             ++j;
 56         }
 57         else if (j == 0)
 58         {
 59             ++i;
 60         }
 61         else
 62         {
 63             j = nextVal[j];
 64         }
 65     }
 66
 67     if (j >= nLenT)
 68     {
 69         return i - nLenT;
 70     }
 71     else
 72     {
 73         return 0;
 74     }
 75 }
 76
 77 int main(int argc, char* argv[])
 78 {
 79     char* S = "ababcabcacbab";
 80     char* T = "abcac";
 81     printf("position = %d\n",IndexKMP(S,T));
 82     return 0;
 83 }
 84
 85


原创粉丝点击