转自:http://blog.csdn.net/tkd03072010/article/details/6824326
——————————————————————————————————
- package arithmetic;
-
- public class KMPTest {
- public static void main(String[] args) {
- String s = "abbabbbbcab";
- String t = "bbcab";
- char[] ss = s.toCharArray();
- char[] tt = t.toCharArray();
- System.out.println(KMP_Index(ss, tt));
- }
-
-
- public static int[] next(char[] t) {
- int[] next = new int[t.length];
- next[0] = -1;
- int i = 0;
- int j = -1;
- while (i < t.length - 1) {
- if (j == -1 || t[i] == t[j]) {
- i++;
- j++;
- if (t[i] != t[j]) {
- next[i] = j;
- } else {
- next[i] = next[j];
- }
- } else {
- j = next[j];
- }
- }
- return next;
- }
-
-
- public static int KMP_Index(char[] s, char[] t) {
- int[] next = next(t);
- int i = 0;
- int j = 0;
- while (i <= s.length - 1 && j <= t.length - 1) {
- if (j == -1 || s[i] == t[j]) {
- i++;
- j++;
- } else {
- j = next[j];
- }
- }
- if (j < t.length) {
- return -1;
- } else
- return i - t.length;
- }
- }
Java实现KMP算法
原文:http://www.cnblogs.com/kaikailele/p/4008192.html