C语言——KMP算法与改进

复习一哈:KMP算法_青岛大学_王卓https://www.bilibili.com/video/BV1nJ411V7bd?p=67

结果:

c49b56a93d414765b73179241d17bdab.png

 

 源码用到了c++中的string类

C++——String类https://blog.csdn.net/qq_22046265/article/details/123733246?spm=1001.2014.3001.5502

 

 源码:

#include <iostream>
using namespace std;


void main()
{
    int KMP(string S, string T);
    void GetNext(string T, int next[]);
    int KMPVal(string S, string T);
    void GetNextVal(string T, int nextval[]);
    //声明


    string Sstr{"@"};
    string Tstr(Sstr);
    //初始化,下标0位 不参与查找  有效数据从小标1开始


    Sstr += {"agendahuaidan"};
    Tstr += {"dan"};
    //给 模式串和子串赋值


    cout << "待查找串为" << Sstr << endl << "查找串" << Tstr << endl;

    //next数组查找
    int key = KMP(Sstr, Tstr);//查找
    if (key)
    {
        cout << "默认KMP:查找串在待查找串的第" << key << "位" << endl;;
    }
    else
    {
        cout << "未查找的到!" << endl;
    }


    //nextval数组查找
    int key_val = KMPVal(Sstr, Tstr);//改进查找
    if (key_val)
    {
        cout << "改进KMP:查找串在待查找串的第" << key_val << "位"<<endl;
    }
    else
    {
        cout << "未查找的到!" << endl;
    }
    return ;
}

void GetNext(string T,int next[])
{
    int i = 1,j=0;
    next[0] = -1;
    next[1] = 0;


    while (i<T.size())
    {
        if (j==0||T[i]==T[j])
        {
            i++;
            j++;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
}

int KMP(string S, string T)
{
    int i = 1, j = 1;
    int next[100];


    GetNext(T, next);//得到next数组


    while (i<S.size()&&j<T.size())
    {
        if (j == 0 || S[i] == T[j])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    if (j > T.size() - 1)
    {
        return i - (T.size()-1);//成功
    }
    else
    {
        return 0;//匹配失败
    } 
}

void GetNextVal(string T,int nextval[])
{
    int i = 1,j=0;
    nextval[1] = 0;


    while (i<T.size()-1)
    {
        if (j==0||T[i]==T[j])
        {
            i++;
            j++;
            if (T[i] != T[j])
            {
                nextval[i] = j;
            }
            else
            {
                nextval[i] = nextval[j];
            }
        }
        else
        {
            j = nextval[j];
        }
    }
}

int KMPVal(string S, string T)
{
    int i = 1, j = 1;
    int nextval[100];


    GetNextVal(T,nextval);//得到next数组


    while (i < S.size() && j < T.size())
    {
        if (j == 0 || S[i] == T[j])
        {
            i++;
            j++;
        }
        else
        {
            j = nextval[j];
        }
    }
    if (j > T.size() - 1)
    {
        return i - (T.size() - 1);//成功
    }
    else
    {
        return 0;//匹配失败
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值