编程语言
首页 > 编程语言> > KMP算法

KMP算法

作者:互联网

#include <bits/stdc++.h>

using namespace std;

char ch1[1000005];
char ch2[1000005];
int Next[1000005]={0};

int buildnxt(int x,int y)
{
    if(y<0) return 0;
    if(ch2[Next[y]]==ch2[x]) return Next[y]+1;
    return buildnxt(x,Next[y]-1);
}

int main(){
    cin>>ch1>>ch2;
    int len1=strlen(ch1);
    int len2=strlen(ch2);
    for(int i=1;i<len2;++i){
        Next[i]=buildnxt(i,i-1);
    }
    int tar=0,pos=0;
    while(tar<len1){
        if(ch1[tar]==ch2[pos]){
            if(pos==len2-1){
                cout<<tar-pos+1<<endl;
                pos=Next[pos];
            }else{
                pos++;
            }
                tar++;
        }else if(pos){
            pos=Next[pos-1];
        }else{
            tar++;
        }
    }
    for(int i=0;i<len2;++i){
        cout<<Next[i];
        if(i<len2-1) cout<<" ";
    }
    return 0;
}

标签:tar,int,ch2,pos,ch1,算法,KMP,Next
来源: https://blog.csdn.net/m0_62325831/article/details/121871880