Java代码
import java.io.*;
/**
* @author jeffery.ma
* @date 2022/10/24 13:56
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
String ps = ' ' + br.readLine();
int m = Integer.parseInt(br.readLine());
String ss = ' ' + br.readLine();
int[] ne = new int[ps.length()];
char[] p = ps.toCharArray();
char[] s = ss.toCharArray();
for (int i = 2, j = 0; i <= n; i ++) {
while (j > 0 && 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 > 0 && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j ++;
if (j == n) {
bw.write(i - n + " ");
j = ne[j];
}
}
bw.flush();
}
}
标签:ps,int,ne,br,KMP,new,readLine
From: https://www.cnblogs.com/antidogmatist/p/16888971.html