Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.22 KB | None | 0 0
  1. #include <string.h>
  2.  
  3. int
  4. boyer_moore(const char *hs,   /* haystack string */
  5.             int hc,           /* sizeof haystack */
  6.             int hp,           /* start of search position */
  7.             const char *ns,   /* needle string */
  8.             int nc) {         /* sizeof needle */
  9.   int skiptable[256];
  10.   int idx;
  11.   int skip;
  12.   const char *cs;
  13.   const char *ce;
  14.   int nlen_minus_1;
  15.  
  16.   /* initialize skiptable to length of needle */
  17.   for(idx=0; idx<256; ++idx)
  18.     skiptable[idx] = nc;
  19.   /* skiptable[idx] = last index of codepoint[idx]
  20.      in needle */
  21.   nlen_minus_1 = nc - 1;
  22.   cs = ns;
  23.   for(idx=nlen_minus_1; idx>0; --idx)
  24.     skiptable[*cs++] = idx;
  25.  
  26.   cs = hs;
  27.   ce = hs + hc;
  28.  
  29.   while( cs < ce ) {
  30.     idx = nlen_minus_1;
  31.     while( idx >= 0 && ns[idx] == cs[idx] )
  32.       --idx;
  33.     if(idx > 0) {
  34.       /* MISMATCH */
  35.       int add;
  36.       skip = skiptable[cs[idx]];
  37.       if(skip!=nc) {
  38.         /* GOOD SUFFIX */
  39.         add = idx + skip - nlen_minus_1;
  40.         if(add<0)
  41.           add = 1;
  42.       } else
  43.         /* BAD CHAR */
  44.         add = idx + 1;
  45.       cs += add;
  46.     } else {
  47.       idx = (int)(cs - hs);
  48.       goto finished;
  49.     }
  50.   }
  51.   idx = -1;
  52. finished:
  53.   return idx;
  54. }
  55.  
  56.  
  57. int
  58. main(void) {
  59. #define TEST(HAY,POS,NDL) do {                                       \
  60.   const char *hay = (HAY);                                           \
  61.   const char *ndl = (NDL);                                           \
  62.   int haylen = strlen(hay);                                          \
  63.   int ndllen = strlen(ndl);                                          \
  64.   int pos = (POS);                                                   \
  65.   pos = boyer_moore(hay,haylen,pos,                                  \
  66.                     ndl,ndllen);                                     \
  67.   if(pos<0)                                                          \
  68.     printf("<%s> not found in <%s>\n", ndl, hay + (POS));            \
  69.   else                                                               \
  70.     printf("<%s> found in <%s> at position %d\n", ndl, hay, pos);    \
  71. } while(0)
  72.  
  73.   TEST("MEOW", 0, "OW");
  74.   TEST("OOOPSOOOPSDOO", 0, "OOPS");
  75.   TEST("xxxxBooooxxxx", 2, "Boooo");
  76.   return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement