AcWing 831. KMP字符串-java
原题链接
简单
作者:
Susu
,
2020-01-28 15:20:38
,
所有人可见
,
阅读 561
import java.io.*;
public class Main{
static int N = 10010;
static int M = 100010;
static char[] s = new char[M];
static char[] p = new char[N];
static int[] ne = new int[M];
static int m;
static int n;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(br.readLine());
String str = br.readLine();
for(int i=1;i<=n;i++){
p[i] = str.charAt(i-1);
}
int m = Integer.valueOf(br.readLine());
str = br.readLine();
for(int i=1;i<=m;i++){
s[i] = str.charAt(i-1);
}
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){
System.out.print(i-n+" ");
j = ne[j];
}
}
}
}