题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1711
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int casesNumber = scn.nextInt();
while (0 <= --casesNumber) {
int modelLength = Integer.parseInt(scn.next());
int patternLength = Integer.parseInt(scn.next());
Kmp kmp = new Kmp(modelLength, patternLength);
for (int i = 0; i < modelLength; ++i) {
kmp.setModelItem(i, Integer.parseInt(scn.next()));
}
for (int i = 0; i < patternLength; ++i) {
kmp.setPatternItem(i, Integer.parseInt(scn.next()));
}
System.out.println(kmp.match());
}
scn.close();
}
}
class Kmp {
private int modelLength;
private int patternLength;
private int[] model;
private int[] pattern;
private int[] next;
private void calculateNext() {
int i = 0, j = -1;
next[0] = -1;
while (i < patternLength - 1) {
if (j == -1 || pattern[i] == pattern[j]) {
++i;
++j;
if (pattern[i] != pattern[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
}
public Kmp(int modelLength, int patternLength) {
this.modelLength = modelLength;
this.patternLength = patternLength;
model = new int[modelLength];
pattern = new int[patternLength];
next = new int[patternLength];
}
public int match() {
calculateNext();
int i = 0, j = 0;
while (i < modelLength && j < patternLength) {
if (j == -1 || model[i] == pattern[j]) {
++i;
++j;
} else {
j = next[j];
}
}
if (j != patternLength) {
return -1;
}
return i - patternLength + 1;
}
public void setModelItem(int i, int value) {
model[i] = value;
}
public void setPatternItem(int i, int value) {
pattern[i] = value;
}
}