KMP

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 8, M = 1e6 + 2;

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

int main(){
    // p --> 模板串  s --> 模式串 ,即 p 是 s 子串
    cin>> n >> p + 1  >> m >> s + 1;
    
    // next 匹配过程
    for(int i = 2, j = 0; i <= n; i++){
        while(j && p[i] != p[j+1]) j = ne[j];
        if(p[i] == p[j+1]) j ++;
        ne[i] = j;
    }
    
    //KMP匹配过程
    for(int i = 1, j = 0; i <= m; i++){
        while(j && s[i] != p[j+1]) j = ne[j];
        if(s[i] == p[j+1]) j++;
        if(j == n){
            printf("%d ", i - n);
            j = ne[j];
        }
    }
    
    return 0;
}

posted @ 2021-04-20 16:05  Carrot_Rui  阅读(40)  评论(0)    收藏  举报