horspool字符串匹配算法.cpp
也不记得是不是原创了,可能是本菜前两年写的吧,反正突然在微云网盘看到了,拿出来吧。
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <memory.h>
using namespace std;
int arr[27];
void recordmovesteps(const char p[],int n){
memset(arr,0,sizeof(arr));
for(int i = 0;i<27;i++){
arr[i] = n;
}
for(int j=0;j<27;j++){
for(int i=n-2;i>=0;i--){
if(p[i]==j+97){
arr[j] = n-i-1;
break;
}
}
}
}
bool cexist(const char c,const char p[],int n){
for(int i=n-1;i>=0;i--){
if(c==p[i]){
return true;
}
}
return false;
}
int getnextlocation(char c){
return arr[c-97];
}
void printprocess(const char P[],const int Plength,int n){
n -= Plength;
for(int i=0;i<=n;i++){
printf(" ");
printf(" ");
printf(" ");
}
for(int j=0;j<Plength;j++){
printf(" %c ",P[j]);
}
printf("\n");
}
int horspool(const char T[],const char P[],const int Tlength,const int Plength){
int i = Plength-1;
char c;
int temp;
printprocess(P,Plength,i);
while(i<Tlength){
temp = i;
int j=Plength-1;
c = T[i];
while(j>=0&&P[j]==T[i]){
j--;
i--;
}
if(j==-1){
return i+1;
}
if(j>=0&&P[j]!=T[i]){
if(cexist(c,P,j))
printf("主串%c与模式串%c不匹配,模式串中失配位置左侧有%c,模式串向右移动%d位\n",T[i],P[j],c,getnextlocation(c));
else
printf("主串%c与模式串%c不匹配,模式串中失配位置左侧没有%c,模式串向右移动%d位\n",T[i],P[j],c,getnextlocation(c));
}
i = getnextlocation(c) + temp;
printprocess(P,Plength,i);
}
return -1;
}
int main()
{
char T[] = "failureeisathebmotherccfdsuccess";
char P[] = "succe";
int Tlength = sizeof(T)/sizeof(char) -1;
int Plength = sizeof(P)/sizeof(char) -1;
if(Plength>Tlength){
printf("模式串长度大于主串,匹配失败");
return 0;
}
for(int i = 0;i<Tlength;i++){
printf("%2d ",i);
}
printf("\n");
for(int i = 0;i<Tlength;i++){
printf(" %c ",T[i]);
}
printf("\n");
recordmovesteps(P,Plength);
int loc = horspool(T,P,Tlength,Plength);
if(loc!=-1){
printf("匹配成功,匹配位置为");
cout << loc <<endl;
}
else
printf("匹配失败,未在主串中找到模式串");
return 0;
}
运行效果:
