#include<stdio.h>
#include <iostream>
#include <string.h>
int table[256];
int skip( char *p,int m){
for(int i=0;i<256;i++)
table[i]=m;//initialize the all the value of table firstly
for(int j=0;j<m-1;j++){
table[p[j]]=m-1-j;// from left scan the pattern
}
return *table;//return the value of table
}
int horspool(char *p,char *t,int m,int n){
skip(p,m);//call function skip
int i=m-1;
while(i<=n-1){
int k=0;//at first the number of match is zero
while(k<m&&p[m-1-k]==t[i-k]){//match the pattern by character ;zhuzi zhuzi de pipei
k++;
}
if(k==m)
return i-m+1;//match successly,return the number
else
i=table[t[i]]+i;//fail,go on skipping
}
return -1;//finally fail return -1
}
int main(){
char p[256];
char t[256];
scanf("%s%s",&p,&t);
int m=strlen(p);
int n=strlen(t);
int x=horspool(p,t, m,n);
printf("%d",x);
}
-
创建移动表.
-
首先初始化所有的字符跳转距离为模式文本pattern的长度,其次再从数组下标0号开始计算它到字符串的串尾元素的距离。
-
串尾元素不参与计算,默认为字符串长度,如果在非串尾的位置出现了和串尾元素相等的元素则用那个计算出来的跳转值覆盖掉默认的串尾元素的跳转值。
-
执行horspool函数,进行匹配。首先初始化k=0表示匹配的字符个数为0,给一个循环:在满足k<pattern的长度时,后面一个个的进行匹配。跳出循环时,当k=pattern的长度时,代表已经匹配成功;如果k不等于pattern的长度 说明没有匹配到,那我们就移动表,移动的值通过先前创建的移动表来读取。
-
如果跳出大循环,说明在整个文本中都不能匹配pattern,则输出-1.结束程序。