字符串匹配--Hospoll算法

一、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;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值