您的位置:首页 > 其它

To_review_100_3---Sunday算法的整理

2015-06-24 21:45 316 查看
PS:前两天在看KMP算法以及BM算法时被虐哭了= =,今天看Sunday算法感觉好爽^_^,后面再整理几个模式匹配的算法,最后比较一下这几个模式匹配算法的性能

思路:

    遇到模式串与主串不匹配时,根据主串中参加匹配的最末字符的下一位字符R的情况,模式串向右进行移动:

    1. 当模式串中不存在R时,直接越过R,向右移动模式串长度+1

    2. 当模式串中存在R时,找出模式串中最右的R'=R,并向右移动模式串,使得模式串的R’对上主串的R

例子:

    STEP1——

       主串:s u b s t  r  i n g _ s e a r c h i n g

    模式串:s e a r c h

    STEP2——

       主串:s u b s t  r  i  n g _  s e a r c h i n g

    模式串:                    s e a  r  c h

    STEP3——

       主串:s u b s t  r  i  n g _  s e a r c h i n g

    模式串:                              s e a r c h

     END

C++代码:

void MakeShift(char* ptrn, int pLen, int* shiftArray, int arrayLen = 256){

 for (int i = 0; i < arrayLen; i++)

  *(shiftArray + i) = pLen + 1;

 while (pLen != 0)

  *(shiftArray + (unsigned char)*ptrn++) = pLen--;

}

bool SundaySearch(char *buf, int bLen, char *ptrn, int pLen, int* shiftArray, int arrayLen=256){

 int b_idx = pLen;

 if (bLen < pLen || bLen == 0 || pLen == 0)

  return false;

 

 while (b_idx <= bLen){

  int p_idx = 0;

  int temp_idx=b_idx-pLen;

  while (*(buf + temp_idx++) == *(ptrn + p_idx++)){

   if (p_idx == pLen)

    return true;

  }

  b_idx += shiftArray[*(buf+b_idx)];

 }

 return false;

}

int main(){

 int shiftArray[256];

 char *buf = "aabd";

 int bLen = 4;

 char *ptrn = "abd";

 int pLen = 3;

 MakeShift(ptrn, pLen, shiftArray);

 cout << SundaySearch(buf, bLen, ptrn, pLen, shiftArray) << endl;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: