题目描述:
求出子串p在串d中出现的位置下标,可能不止出现一次。
package likou;
import java.util.Scanner;
public class KMP {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int N = 999;
char[] p = new char[N];
char[] s = new char[N];
int[] next = new int[N];
String temp_p = scanner.next();
String temp_s = scanner.next();
temp_p = " "+temp_p;//前面加一个空格,这样转成字符串数组,能保证输入的串从下标1开始计数
temp_s = " "+temp_s;
p = temp_p.toCharArray();
s = temp_s.toCharArray();
//求子串p的next数组
for(int i =2,j=0;i<temp_p.length();i++){
while(j!=0&&p[i]!=p[j+1])
j = next[j];
if(p[i]==p[j+1])
j++;
next[i] = j;
}
//KMP匹配
for(int i = 1,j=0;i<temp_s.length();i++){
while(j!=0&&s[i]!=p[j+1])
j=next[j];
if(s[i]==p[j+1])
j++;
if(j==temp_p.length()-1){
System.out.println(i-temp_p.length()+1);
j=next[j];//可能不止一次出现
}
}
}
}
}