关于算法:kmp实现

41次阅读

共计 453 个字符,预计需要花费 2 分钟才能阅读完成。

#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;
}

正文完
 0