#include <iostream>
using namespace std;
const int N = 100010, M = 1000010;
int n, m;
int ne[N];
char p[N], s[M];
int main(){
cin >> n >> p + 1 >> m >> s + 1;
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;
}
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) {
cout << i - n << " ";
j = ne[j];
}
}
return 0;
}
var strStr = function(haystack, needle) {
if ( haystack == "" && needle == ""){
return 0;
}
let len1 = needle.length;
let len2 = haystack.length;
const ne = new Array(len1).fill(0);
for ( let i = 1, j = 0; i < len1; i ++ ) {
while ( j > 0 && needle[i] !== needle[j] ) j = ne[j - 1];
if ( needle[i] == needle[j] ) j ++;
ne[i] = j;
}
for ( let i = 0, j = 0; i < len2; i ++ ) {
while ( j > 0 && haystack[i] != needle[j]) j = ne[j - 1];
if ( haystack[i] == needle[j] ) j ++;
if (j == len1 ){
return i - len1 + 1;
}
}
return -1;
};
四月份结束会KMP就行,要求不高😓。
|