#include <iostream>
using namespace std;
const int N = 100010, M = 1000010; // N 为匹串长度, M 为模式串长度
int n, m;
int ne[N];
char p[N], s[M]; // p 为匹配串, s 为模式串
int main(){
cin >> n >> p + 1 >> m >> s + 1; // 从下标为1开始
// 求 next[] 数组
// index 1 2 3
// value 0 0 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;
}
// 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) {
cout << i - n << " ";
j = ne[j];
}
}
return 0;
}
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
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);
// next[] 数组
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;
}
// KMP
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就行,要求不高😓。