C语言实现KMP算法(定长顺序存储表示字符串)

定长顺序存储表示字符串,用KMP算法找出模式串

串S = ‘aafhjkxdeeshtksslshtvdfdhshtksslshtbfdmhgshtksslshtsfesrgb’
用定长顺序存储表示字符串,用KMP算法找出模式串T=‘shtksslsht’出现在主串S(执行添加和删除操作之前的S)中的所有位置(不止一个),并打印输出。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

#define maxlen 255

typedef char sstring[maxlen + 1];

int InitStr(sstring s)
{
    s[0] = 0;
    return 1;
}
int strLength(sstring s)
{
    return s[0];
}

int strAssign(sstring s, sstring c)
{
    int i;
    for (i = 0; c[i] != '\0' && i + 1 < maxlen; i++)
    {
        s[i + 1] = c[i];
    }
    s[i + 1] = '\0';
    s[0] = i;
    return 1;
}
void clears(sstring s)
{
    s[0] = 0;
}

int strEmpty(sstring s)
{
    if (s[0] == 0)
        return 1;
    else
        return 0;
}
void Next(sstring T, int *next)
{
    int i = 1;
    next[1] = 0;
    int j = 0;
    while (i < strlen(T))
    {
        if (j == 0 || T[i - 1] == T[j - 1])
        {
            i++;
            j++;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
}
int Index_KMP(sstring S, sstring T, int pos)
{
    int next[10];
    Next(T, next); //根据模式串T,初始化next数组
    int i = pos;
    int j = 1;
    while (i <= strlen(S) && j <= strlen(T))
    {
        //j==0:代表模式串的第一个字符就和当前测试的字符不相等;S[i-1]==T[j-1],如果对应位置字符相等,两种情况下,指向当前测试的两个指针下标i和j都向后移
        if (j == 0 || S[i - 1] == T[j - 1])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j]; //如果测试的两个字符不相等,i不动,j变为当前测试字符串的next值
        }
    }
    if (j > strlen(T))
    { //如果条件为真,说明匹配成功
        return i - (int)strlen(T);
    }
    return 0;
}
int main()
{
    sstring s, in;
    InitStr(s);
    InitStr(in);
    strAssign(s, "aafhjkxdeeshtksslshtvdfdhshtksslshtbfdmhgshtksslshtsfesrgb");
    strAssign(in, "shtksslsht");
    int i;
    while (i = Index_KMP(s + 1, in + 1, i))
    {
        printf("%d ", i);
        i++;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值