See More

package string; //×Ö·û´®Æ¥ÅäËã·¨ public class KMPTest { public static void main(String[] args) { KMP kmp = new KMP(); String s ="aaaaaaaaaaaaabaaaaaaaaaaaaaabcdefd"; String t ="aaaaaab"; System.out.println(kmp.indexKMP(s, t, 1)); } } class KMP { public void getNext(String t, int[] next) { char[] t1 =(" " +t).toCharArray(); //ÓÃÀ´×öºóÃæµÄ×Ö·û´®±È½Ï£¬µ«µÚÒ»¸ö×Ö·ûµÄ±êºÃΪ1£¬¹Ê¼ÓÒ»¸ö¿Õ¸ñ int i=1; int j=0; next[1] = 0; while(i < t.length()) { if( j == 0 || t1[i] ==t1[j]) { i++; j++; next[i] = j; //----------------¸Ä½øµÄ²¿·Ö----------- if(t1[i] != t1[j]) //Èôµ±Ç°×Ö·ûÓëǰ׺×Ö·û²»Í¬ next[i] =j; //Ôòµ±Ç°µÄjΪnextÔÚiλÖõÄÖµ else //Èç¹ûÓëǰ׺×Ö·ûÏàͬ£¬Ôò½«Ç°×º×Ö·ûµÄnextÖµ¸³¸ønextÔÚiλÖõÄÖµ next[i] = next[j]; } else j = next[j]; //Èô×Ö·û²»Ïàͬ£¬ÔòjÖµ»ØËÝ } } //·µ»Ø×Ó´®tÔÚÖ÷´®sÖеÚpos¸ö×Ö·ûÖ®ºóµÄλÖã¬Èô²»´æÔÚ£¬Ôòº¯Êý·µ»ØÖµÎª0 //T·Ç¿Õ£¬ 1<= pos <=s.length(); public int indexKMP(String s, String t, int pos) { int i =pos; int j =1; int[] next = new int[255]; //¶¨ÒåÒ»¸önextÊý×é //±È½ÏµÄʱºò¶¼ÊÇ´ÓÊý×éµÄλÖÃ1¿ªÊ¼µÄ£¬¹Ê½«Î»ÖÃ0ÓÿոñÌî³ä char[] s1 = (" "+ s).toCharArray(); char[] t1 = (" " + t).toCharArray(); getNext(t,next); while(i<= s.length() && j<= t.length()) //ÈôiСÓÚsµÄ³¤¶ÈÇÒjСÓÚtµÄ³¤¶È£¬Ñ­»·¼ÌÐø { if(j ==0 || s1[i] == t1[j]) { i++; j++; } else //Ö¸ÕëºóÍËÖØÐ¿ªÊ¼Æ¥Åä { j = next[j]; //jÍ˻غÏÊʵÄλÖã¬iÖµ²»±ä } } if(j > t.length()) return i - t.length(); else return 0; } }