KMP算法学习

/*
    字符串匹配算法
    第二个算法:KMP匹配法
    函数名:str_match
*/
#include<stdio.h>
#include<string.h>
#define MXLEN 100
/*
    strs为主串,strp为模式串
    若不存在匹配,则返回-1
*/
int str_match(const char* strs, const char* strp);
int main()
{
    char strs[MXLEN], strp[MXLEN];
    int pos;
    while(scanf("%s%s", strs, strp) != EOF)
    {
        pos = str_match(strs, strp);
        if(-1 == pos)
        {
            printf("No match string./n");
        }
        else
        {
            printf("match position: %d/n", pos);
        }
    }
    return 0;
}
void get_next(int next[], const char* str)
{
    int i=0, k=-1;
    next[0] = -1;
    while(str[i+1])
    {
        if(-1==k || str[i]==str[k])
        {
            i++, k++;
            /* 假设str[i] == str[k],那么,如果对str[i]匹配失败,*/
            /* 对str[k]匹配也必然是失败的,故可直接滑动到next[k] */
            if(str[i] != str[k])
            {
                next[i] = k;
            }
            else
            {
                next[i] = next[k];
            }
        }
        else
        {
            k = next[k];
        }
    }
    return ;
}
int str_match(const char* strs, const char* strp)
{
    int next[MXLEN];
    int i=0; /* 指向主串下标 */
    int k=0; /* 指向模式串下标 */
    get_next(next, strp);
    while(-1==k || strs[i] && strp[k])
    {
        if(-1==k || strs[i]==strp[k])
        {
            i++;
            k++;
        }
        else
        {
            k = next[k];
        }
    }
    if(strp[k])
    {
        /* 匹配失败 */
        return -1;
    }
    return i-k;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值