AcWing 831. JAVA_短_KMP字符串
原题链接
简单
作者:
acw_weian
,
2020-04-19 15:49:53
,
所有人可见
,
阅读 565
import java.io.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
int m = Integer.valueOf(read.readLine());
char[] p = (" " + read.readLine()).toCharArray();
int n = Integer.valueOf(read.readLine());
char[] s = (" " + read.readLine()).toCharArray();
int[] ne = new int[m + 1];
// 求 next的过程
for (int i = 0, j = 2; j <= m; j++) { // i = 1的时候只有一个元素, 最长前缀的长度为 0
while (i != 0 && p[j] != p[i + 1]) i = ne[i];
if (p[j] == p[i + 1]) i++;
ne[j] = i;
}
// kmp匹配过程
// j指向 s将要匹配的位置, i指向已经匹配模板串已经匹配成功的位置
for (int i = 0, j = 1; j <= n; j++) {
while (i != 0 && s[j] != p[i + 1]) i = ne[i];
if (s[j] == p[i + 1]) i++;
if (i == m) {
log.write(j - m + " ");
i = ne[i];
}
}
log.flush(); // 关闭输入输出流
read.close();
log.close();
}
}
强啊 还能这么转数组