AcWing 831. KMP字符串
原题链接
简单
作者:
pqp
,
2025-03-27 22:10:17
·天津
,
所有人可见
,
阅读 1
import java.util.*;
public class Main
{
static final int N = 1000010;
static final int M = 100010;
static int[] pm = new int[M];
static int n,m;
static String p,s;
static void get_pm()
{
pm[0] = 0;
int i = 1;
int len = 0;
while(i < p.length())
{
if(p.charAt(len) == p.charAt(i))
{
len++;
pm[i] = len;
i++;
}
else
{
if(len == 0)
{
pm[i] = 0;
i++;
}
else len = pm[len-1];
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
p = sc.next();
m = sc.nextInt();
s = sc.next();
get_pm();
for(int i = 0, j = 0; i < s.length();)
{
if(s.charAt(i) == p.charAt(j))
{
i++;
j++;
}
else
{
if(j == 0) i++;
else j = pm[j-1];
}
if(j == p.length())
{
System.out.print(i - j + " ");
j = pm[j-1];
}
}
}
}