See some of the KMP realization, according to gourd painting scoop, very rigid, prefix what is completely unnecessary.
KMP The core idea of the algorithm: first to the search string generation offset comparison table, matching from left to right in order to compare (bm from right to left, claiming to be faster than KMP), equal to the document and search string subscript +1 iteration, otherwise check the table, positioning the optimal offset position (document subscript unchanged, search string subscript change). The exception is, if the character does not match, if the search string subscript is 0, then the document subscript +1, continue the iteration comparison.
Import Java.util.arrays;public class Kmpsearch {public static int[] table;public static void Generatetab (String key) {//query The string generates an offset table, an iteration can be int len=key.length (); table=new Int[len]; Arrays.fill (table, 0), for (int i=1;i<len;i++) {if (Key.charat (i) ==key.charat (Table[i-1])) {table[i]=table[i-1]+1;}} for (int v:table) {System.out.print (v);} System.out.println ();} public static int Kmpsearchs (String doc,string key) {Generatetab (key); int Result=-1;int doc_size=doc.length (), key_size =key.length (), Doc_iter=0,key_iter=0;while (doc_iter<doc_size) {//traverse the document being queried, again, a single-layer loop can implement →_→ if (Doc.charat (doc_ ITER) ==key.charat (Key_iter)) {doc_iter++;key_iter++;} Else{if (key_iter==0) {doc_iter++;continue;} Else{key_iter=table[key_iter-1];continue;}} if (key_iter==key_size) {result=doc_iter-key_size;break;}} return result;} public static void Main (string[] args) {int I=kmpsearchs ("BBC Abcdab Abcdabcdabde", "abcdabd"); System.out.println (i);}}
Algorithm explanation Reference HTTP://ITINDEX.NET/DETAIL/45421-%E5%AD%97%E7%AC%A6%E4%B8%B2-%E5%8C%B9%E9%85%8D-KMP
String matching algorithm KMP Java implementation