自己写得kmp算法,暂时放在这里

#if 0
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

#define MAX_PATTERN_LEN 1024

//print the array
void print(int *a, int n)
{
         printf("next:");
         int i;
         for(i = 0; i < n; ++i) printf("%d ", a[i]);
         printf("\n");
}

//generate a random string
void randstr(char a[], int n)
{
         int i;
         for(i = 0; i < n; i++)
                a[i] = 'a' + rand() % 3;

         a[n - 1] = '\0';
}

//preprocessing for KMP
void preKMP(const char* t, int next[], int len)
{
         int i,j;
         next[0] = -1; //Attention: next[0] equals -1 other than 0
         i = 0;
         j = -1;
         while(i < len)
         {
                 while(j > -1 && t[j] != t[i])
                          j = next[j];

                 i++, j++;
                 if(t[j] == t[i])
                         next[i] = next[j];
                 else
                        next[i] = j;
          }
          print(next, len);//output  the 'next' array
}

// KMP, ensure strlen(t) < MAX_PATTERN_LEN
int KMP(const char* s, const char* t)
{
          int next[MAX_PATTERN_LEN];
          int lens = strlen(s);
          int lent = strlen(t);
          preKMP(t, next, lent);
          int i,j;
          i = j = 0;
          while(i < lens)
         {
                  while(j > -1 && t[j] != s[i])
                          j = next[j];
                  i++, j++;
                  if(j >= lent) return i - j;
         }
         return -1;
}

int main(int argc, char** argv)
{
        srand(time(NULL));
        int times = 20;
        while(--times)
        {
                char s[1024];
                char t[1024];
                randstr(s, 100);
                randstr(t, 5);
                printf("S:%s\nT:%s\n", s, t);
                int r1 = KMP(s, t);
                char* r2 = strstr(s, t);
 
                printf("%d:%s\n", r1, r2);
                if(r1 == -1 && r2 == NULL || r1 == r2 - s) printf("check:TRUE ^_^\n");
               else printf("check:FALSE XXX\n");
               printf("----------------------------------------------------\n");
       }
       system("pause");
       return 0;
}


#endif

你可能感兴趣的:(KMP)