AcWing 831. JAVAKMP字符串
原题链接
简单
作者:
ARM
,
2020-08-06 22:37:04
,
所有人可见
,
阅读 363
java 代码
import java.io.*;
import java.lang.Integer;
class Main{
static void next(int[] next, String s){//构造next前后缀数组
int len = s.length();
int i = 0, j = -1;
next[0] = -1;
while(i < len){
if(j == -1 || s.charAt(i) == s.charAt(j)){
i++;
j++;
next[i] = j;
}else{
j = next[j];
}
}
}
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter buw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.valueOf(buf.readLine());
String s = buf.readLine();
int m = Integer.valueOf(buf.readLine());
String p = buf.readLine();
int[] next = new int[n + 10];//其实加1就可以了,因为kmp求next数组需要用到length+1位
next(next, s);
int i = 0, j = 0;
while(i < m && j < n){
if(j == -1 || p.charAt(i) == s.charAt(j)){//j == -1的目的是如果整个串都不匹配只能让i,j向后移动一位,重新开始匹配
i++;
j++;
}else{
j = next[j];
}
if(j == n){
buw.write(i - j + " ");
System.out.print(j);
j = next[j];//匹配完成,j返回上一步
}
}
buw.flush();
buf.close();
buw.close();
}
}