Horspool(字符串匹配)算法实现 c语言

#include

#define ASIZE 256

void preBmBc(char *x, int m, int bmBc[]) {
   int i;
 
   for (i = 0; i < ASIZE; ++i)
      bmBc[i] = m;
   for (i = 0; i < m - 1; ++i)
      bmBc[x[i]] = m - i - 1;
}

void HORSPOOL(char *x, int m, char *y, int n) {
   int j, bmBc[ASIZE];
   char c;

   /* Preprocessing */
   preBmBc(x, m, bmBc);

   /* Searching */
   j = 0;
   while (j <= n - m) {
      c = y[j + m - 1];
      if (x[m - 1] == c && memcmp(x, y + j, m - 1) == 0)
         printf("%.*s", m, y +j);
      j += bmBc[c];
   }
   printf("\n");
}



int main()
{
    char *pattern = "hello";
    char *buf = "hehe  hello world";
    HORSPOOL(pattern, strlen(pattern), buf, strlen(buf));
    return 0;
}

 

你可能感兴趣的:(算法)