纯模板 记忆使用~
class Main {
static char[] s1;
static char[] s2;
static int[] next;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
s1 = in.nextLine().toCharArray();
s2 = in.nextLine().toCharArray();
int m = s2.length;
int n = s1.length;
next = new int[m + 1];
getNext();
//System.out.println(Arrays.toString(next));
List<Integer> res = new ArrayList<>();
int i = 0, j = 0;
while(i < n){
if(j == -1 || s1[i] == s2[j]){
i++;
j++;
}else{
j = next[j];
}
if(j == m){//可重复匹配版本 单个匹配直接break
res.add(i - j);
i = i - j + 1;
j = 0;
}
}
for(int re: res)
System.out.println(re + 1);
}
static void getNext(){
next[0] = -1;
int m = s2.length;
int k = -1;
int j = 0;
while(j < m){
if(k == -1 || s2[k] == s2[j]){
++k;
++j;
next[j] = k;
}else{
k = next[k];
}
}
}
}
标签:JAVA,int,s2,s1,next,++,static,KMP,模板
From: https://www.cnblogs.com/ganyq/p/18197888