KMP算法

#include <iostream>
using namespace std;
int f[20];
#define MAX 20
typedef struct
{
    char ch[MAX];
    int len;
}_string;
int _length(_string *s)
{
    int i=0;
    while(s->ch[i]!='')
        i++;
    return i;
}
int concat(_string *s1,_string *s2)
{
    int len1=_length(s1);
    int len2=_length(s2);
    int i;
    for(i=len1;i<len1+len2;i++)
        s1->ch[i]=s2->ch[i-len1];
    s1->ch[i]='';
}
int cmp(_string *s1,_string *s2)
{
    int i=0;
    while(s1->ch[i]==s2->ch[i])
        i++;
    return s1->ch[i]-s2->ch[i];
}
int _index(_string *s1,_string *s2)
{
    int i,j;
    int len1=_length(s1),len2=_length(s2);
    for(i=0;i<=len1-len2;i++)
    {
        for(j=i;j<len2;j++)
            if(s1->ch[j]!=s2->ch[j])
                break;
        if(j==len2)
            return i+1;
    }
}
int sub(_string *s1,_string *s2,int x,int y)
{
    int i,j=0;
    if(x<0||y<=0||x+y-1>_length(s1)||x>_length(s1))
        return 0;
    else
    {
        for(i=x-1;i<x+y-1;i++)
            s2->ch[j++]=s1->ch[i];
    }
    s2->ch[j]='';
}
int del(_string *s1,int x,int y)
{
    if(x<0||y<=0||x>_length(s1)||x+y-1>_length(s1))
        return 0;
    int len=_length(s1);
    int i,j=x-1;
    for(i=x+y-1;i<len;i++)
        s1->ch[j++]=s1->ch[i];
    s1->ch[j]='';
}
int insert(_string *s1,_string *s2,int x)
{
    int len1=_length(s1),len2=_length(s2);
    if(len1+len2>MAX||x>len1||x<0)
        return 0;
    else
    {
        int i,j=0;
        for(i=len1;i>=x-1;i--)
            s1->ch[i+len2]=s1->ch[i];
        for(i=x-1;i<x+len2-1;i++)
            s1->ch[i]=s2->ch[j++];
    }
}
int kmpmatch(_string *t,_string *p)    /*kmp匹配算法*/
{
    int len1=_length(t),len2=_length(p);
    int i=0,j=0;
    while(i<len1&&j<len2)
    {
        if(j==-1||t->ch[i]==p->ch[j])    /*如果j==-1或者当前字符匹配相等,则继续比较后面的字符*/
        {
            i++;
            j++;
        }
        else
            j=f[j];        /*当匹配不相等时,则j退回到f(j)中,即求出所谓的k值*/
    }
    if(j>=len2)
        return i-len2+1;
    return -1;
}
int next(_string *p)        /*失效函数*/
{
    int len=_length(p);
    f[0]=-1;
    int k=-1,j=0;
    while(j<len)
    {
        if(k==-1||p->ch[j]==p->ch[k])
        {
            k++;
            f[++j]=k;
        }
        else
            k=f[k];
    }
}
int main()
{
    _string s1,s2;
    //cin>>s1.ch>>s2.ch;
    /*cout<<_length(&s1)<<endl;
    concat(&s1,&s2);
    cout<<s1.ch<<endl;
    cout<<cmp(&s1,&s2)<<endl;
    cout<<_index(&s1,&s2);
    insert(&s1,&s2,2);
    cout<<s1.ch<<endl;*/
    cin>>s1.ch>>s2.ch;
    next(&s1);
    cout<<kmpmatch(&s1,&s2);
    //cout<<kmpmatch(&s1,&s2);
    /*for(int i=0;i<10;i++)
        cout<<f[i]<<" ";*/
    
}
原文地址:https://www.cnblogs.com/a1225234/p/4776772.html