kmp模板

来源:互联网 发布:整理桌面软件 编辑:程序博客网 时间:2024/05/22 04:50

变量及函数名:

a[ ] 母串      b[ ] 子串      m 子串长度      n 母串长度       nextl[ ]  next数组    

pos  子串位置    coun  子串数量   //找第一个子串和统计有多少个子串是两个操作

作为学习总结,写上kmp的思路



#include<bits/stdc++.h>using namespace std;const int maxn=10e3;char a[maxn],b[maxn];int nextl[maxn];void crenext(){   memset(nextl,0,sizeof(nextl));    nextl[0]=-1;    int j;    int m=strlen(b)-1;    for(int i=1;i<=m;i++)    {        j=nextl[i-1];        while(b[j+1]!=b[i]&&j>=0)        {            j=nextl[j];        }        if(b[j+1]==b[i])        nextl[i]=j+1;        else            nextl[i]=-1;    }     for(int i=0;i<=m;i++)      nextl[i]++;      /*for(int i=0;i<m;i++)        cout<<nextl[i]<<" ";*/}int main(){    memset(b,0,sizeof(b));memset(a,0,sizeof(a));    while(cin>>b>>a)    {        crenext();        int m=strlen(b),n=strlen(a);        int i=0,j=0,pos=-1,coun=0;        while(i<n)        {            if(a[i]!=b[j])            {                if(j!=0)                {                    j=nextl[j-1];                }                else                {                    i++;                }            }            else            {                i++;j++;            }            if(j==m){pos=i;break;}     //   if(j==m){coun++;}        }     //   cout<<coun<<endl;    if(pos!=-1)    cout<<pos-m+1<<endl;    else cout<<-1;    }    return 0;}

之前next写太烂了,补一个

经验教训表明搞出来的next还是第一位(下标为0的那个)放一个-1,第二位开始放东西好些

const int maxn=100000;
char b[maxn];
int nextl[maxn];
void getnext()
{
    memset(nextl,0,sizeof(nextl));
    int l=strlen(b);
    nextl[0]=-1;
    int pb=0,pn=-1;
    while(pb<l)
    {
        if(pn==-1||b[pb]==b[pn])
        {
            pb++;
            pn++;
            nextl[pb]=pn;
        }
        else
        {
            pn=nextl[pn];
        }
    }
}


原创粉丝点击