KMP模板

第二次理解了,一个讲的可以的博客:https://blog.csdn.net/starstar1992/article/details/54913261#commentBox

#include<bits/stdc++.h>
using namespace std;
char s1[1000001],s2[1000001];
int next[1000001];

void Next(int len2)
{
    next[0]=-1;
    int k=-1;
    for(int i=1;i<len2;i++)
    {
        while(k>-1&&s2[i]!=s2[k+1])
            k=next[k];
        if(s2[i]==s2[k+1])k++;
        next[i]=k;
    }
}
//abavababababc
//abababc
//-1-1 0 1 2 1 -1
void kmp(int len1,int len2)
{

    for(int i=0,j=-1;i<len1;i++)///是s2的下标-1
    {
        while(s1[i]!=s2[j+1]&&j>-1)
            j=next[j];
        if(s1[i]==s2[j+1])j++;
        if(j==len2-1)
        {
             cout<<i-j+1<<endl;
             j=next[j];
        }

    }
}
int main()
{

    int i;
    scanf("%s%s",s1,s2);int len1=strlen(s1),len2=strlen(s2);
    Next(len2);
    kmp(len1,len2);
    for( i=0;i<len2-1;i++)
      cout<<next[i]+1<<" ";
    cout<<next[i]+1;
    return 0;
}
// BBCABCDABABCDABCDABDE
 //ABCDABD
// 0000120

 

上一篇:【luogu P6091】【模板】原根


下一篇:[CSP-S模拟测试]:e(树上主席树)