数据结构-KMP

暴力求解:

#include <bits/stdc++.h>
using namespace std;
#define maxSize 10
typedef struct
{
    char ch[maxSize+1];  // 多出一个'\0'作为结束标记
    int length;
} Str;
int index(Str S, Str T)
{
    int i = 1, j = 1, k = i;
    while (i<=S.length && j<=T.length)
    {
        if (S.ch[i] == T.ch[j])
        {
            ++i;
            ++j;//继续比较后继字符
        }
        else
        {
            j = 1;
            i = ++k;  // 匹配失败,i从主串的下一位置开始,k中记录了上一次的起始位置
        }
    }
    if (j>T.length) return k;
    else return 0;
}
int main()
{

    return 0;
}

利用next数组:

#include <bits/stdc++.h>
using namespace std;
#define maxSize 10
typedef struct
{
    char ch[maxSize+1];  // 多出一个'\0'作为结束标记
    int length;
} Str;
void GetNext(Str p,int next[])
{
    next[1] = 0;
    int i = 1;
    int j = 0;
    while (i < p.length)
    {
        //p[i]表示前缀,p[j]表示后缀
        if (j == 0 || p.ch[i] == p.ch[j]) //j==0表示第一位就不匹配
        {
            ++i;
            ++j;
            next[i] = j;
        }
        else
        {
            j= next[j];
        }
    }
}

int KMP(Str S, Str T)
{
    int i = 1,j = 1;
    int next[T.length+1];
    GetNext(T,next);
    while (i <=S.length && j <=T.length)
    {
        //如果j = 0,或者当前字符匹配成功(即S[i] == T[j]),都令i++,j++
        if (j == 0 || S.ch[i] == T.ch[j]) //j==0用来防止一开始就匹配不上的特殊情况
        {
            i++;
            j++;
        }
        else
        {
            //如果j != 0,且当前字符匹配失败(即S[i] != T[j]),则令 i 不变,j = next[j]
            //next[j]即为j所对应的next值
            j = next[j];
        }
    }
    if (j >T.length)
        return i - T.length;  // 匹配成功,则返回匹配的位置
    else
        return 0;
}
int main()
{

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值