KMP算法
public class Main {
public static void main(String[] args) {
char s[] = "ababca12341234fgdf".toCharArray();
char t[] = "3412".toCharArray();
int x = search(s, t);
System.out.println(x);
}
private static int[] next(char[] pattern) {
int[] result = new int[pattern.length];
result[0] = -1;
result[1] = 0;
int i = 2;
while (i < pattern.length) {
if ((pattern[i - 1] == pattern[result[i - 1]])) {
result[i] = result[i - 1] + 1;
} else {
result[i] = 0;
}
i++;
}
return result;
}
private static int search(char[] s, char[] t) {
int i = 0, j = 0;
int[] next = next(t);
while (i < s.length) {
if (s[i] == t[j]) {
i++;
j++;
if (j == t.length) {
return i - j;
}
} else {
j = next[j];
if (j == -1) {
j++;
i++;
}
}
}
return -1;
}
}