原理:http://blog.csdn.net/v_july_v/article/details/7041827
讲的只有最详细没有更详细的了
public class KMPTest {
public String originStr = null;
public String moduleStr = null;
public int[] next = null;
public int[] GetNext(String p){
int[] next = new int[p.length()];
next[0] = -1;
int k = -1;
int j = 0;
while (j < p.length()-1) //循环里有++不能越界
{
//k子串从头找匹配的,开始0、1
if (k == -1 || p.charAt(j) == p.charAt(k))
{
++k;
++j;
next[j] = k; //不匹配的其next[]设为0,对匹配的在其下一位的next[]设匹配个数
}
else
{
k = next[k]; //对不匹配的数将k设-1
}
}
return next;
}
public int[] GetNextval(String p){
int[] next = new int[p.length()];
next[0] = -1;
int k = -1;
int j = 0;
while (j < p.length()-1)
{
if (k == -1 || p.charAt(j) == p.charAt(k))
{
++k;
++j;
if (p.charAt(j) != p.charAt(k)) //对不一样的匹配还是原来的求法
next[j] = k;
else
next[j] = next[k]; //对子串中相同值next回溯
}
else
{
k = next[k];
}
}
return next;
}
public void Print(int array[]){
System.out.print("数组:\t");
for(int i=0;i<array.length;i++){
System.out.print(array[i]+"\t");
}
System.out.println("");
}
public int Search(String s,String p){
this.next = GetNext(p);
this.Print(this.next);
this.next = GetNextval(p);
this.Print(this.next);
int i = 0;
int j = 0;
while (i < s.length() && j < p.length())
{
if (j == -1 || s.charAt(i) == p.charAt(j))
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j == p.length())
return i - j;
else
return -1;
}
public static void main(String args[]){
KMPTest ktest = new KMPTest();
int index = ktest.Search("BBC ABCDAB ABCDABCDABDE","ABCDABD");
System.out.println(index);
}
}