kmp实现

crab
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1e5 + 10, M = 1e6 + 10;

char p[N], s[M];
int n,m,ne[N];

int main(){
    cin.tie(NULL); ios::sync_with_stdio(false);
    
    cin >> n >> (p+1) >> m >> (s+1);
    
    int i,j,k;
    j = 1, k = 0, ne[1] = 0;
    while(j <= n){
        if(k == 0 || p[j] == p[k]){ne[j+1] = k+1; j++;k++;}
        else k = ne[k];
    }
    
    i = 1, j = 1;
    while(i <= m){
        if(j == 0 || s[i] == p[j]){
            i++; j++;
            if(j > n) printf("%d%c",i-n-1,i>m?'\n':' ');
        }
        else j = ne[j];
    }
    
//    if(j > n) cout << i-n-1 << endl;
//    else cout << -1 <<endl;
    
    return 0;
}
阅读 517
1 声望
0 粉丝
0 条评论
1 声望
0 粉丝
文章目录
宣传栏