603【模板】KMP 算法


視頻鏈接:603【模板】KMP 算法_嗶哩嗶哩_bilibili

 

Luogu P3375【模板】KMP字符串匹配

#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int N = 1000010;
int m, n;
char S[N], P[N];
int ne[N];

int main(){
    cin >> S+1 >> P+1;
    m = strlen(S+1), n = strlen(P+1);
    // 計算next函數
    ne[1] = 0;
    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\n", i-n+1);
    }
    for(int i = 1; i <= n; i ++)
        printf("%d ", ne[i]);
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM