一、Hospoll算法原理
参考文章:http://blog.csdn.net/jjdiaries/article/details/12771439
本人就不废话了
二、Hospoll算法规则:
字符串后移位数 = 失配字符位置 - 失配字符上一次出现的位置三、在写代码之前需要明白
1、模式串是从右向左进行匹配,匹配过程中,模式串实际上是从左往右做整体挪动2、对模式串的操作:需要找到不匹配元素的位置下标index
3、对主串的操作:
1)找到不匹配元素ch
2)在模式串中找ch元素在Index位置之前是否存在(需从头至index遍历):
a)若存在:返回位置下标(即为失配字符上一次出现的位置)
b)若不存在,则失配字符上一次出现的位置为-1
四、C代码实现
/*************************************************************************
Hospoll算法
代码中的:
text_str : 主串
match_str :模式串
index :不匹配元素的位置下标index
ch :不匹配元素
author:tmw
date:2018-2-26
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**主串中找到的不匹配元素,在模式串中从头至index遍历,找到该元素的下标位置**/
int findIndex(char* match_str , char ch , int index)
{
int i;
for(i=0;i<index;i++)
{
if( match_str[i] == ch )
return i;
}
return -1;
}
int strMatch_Hospool(char* text_str , char* match_str)
{
int i=0;
int j=0;
// 初始化
j = strlen(match_str)-1;
i = j;
while(i<strlen(text_str))
{
if( text_str[i] == match_str[j] )
{
i--;
j--;
if(j<0)
{
printf("找到匹配串! 匹配位置为:[%d ~ %d]\n",i+1,i+strlen(match_str));
return 0;
}
}
else
{
/**此时不匹配的元素为text_str[i],此时不匹配位置对于模式串而言,在它的j位置处
找到不匹配元素在模式串的上一位置是否有相同元素**/
int index = findIndex(match_str,text_str[i],j);
/**Hospoll算法规则
(strlen(match_str)-1-j)里的是为了让i回到相对于match_str的尾部位置,才能与j继续从右往左匹配
**/
i = i + j - index + (strlen(match_str)-1-j);
j = strlen(match_str)-1; //j回退到初始化的位置
printf("%d \n",i);//打印i跳转过的“相对串尾”位置
}
}
printf("未找到匹配串...\n");
return 0;
}
五、测试代码及测试结果
int main()
{
printf("测试代码\n");
char text_str1[20] = "substring searching";
char match_str1[7] = "search";
printf("文本串为:%s\n",text_str1);
printf("匹配串为:%s\n",match_str1);
strMatch_Hospool(text_str1,match_str1);
printf("\n");
char text_str2[20] = "hello world lalala";
char match_str2[7] = "aaa";
printf("文本串为:%s\n",text_str2);
printf("匹配串为:%s\n",match_str2);
strMatch_Hospool(text_str2,match_str2);
char text_str3[40] = "abcbcsdLibac-codecbcac";
char match_str3[7] = "cbcac";
printf("文本串为:%s\n",text_str3);
printf("匹配串为:%s\n",match_str3);
strMatch_Hospool(text_str3,match_str3);
printf("\n");
return 0;
}