public static int matchString(String target, String mode) {
int[] K = calculateK(mode);
int i = 0;
int j = 0;
int count = 0;
while(i < target.length()) {
if (j == -1 || target.charAt(i) == mode.charAt(j)) {
i++;
j++;
} else {
j = K[j];
}
if (j > mode.length() - 1) {
count ++;
j = 0;
}
}
return count;
}
/*
* calculate K array
*/
private static int[] calculateK(String mode) {
int[] K = new int[mode.length()];
int i = 0;
K[0] = -1;
int j = -1;
while(i < mode.length() - 1) {
if (j == -1 || mode.charAt(i) == mode.charAt(j)){
i++;
j++;
K[i] = j;
} else {
j = K[j];
}
}
return K;
}