Public class KMP {static int [] next;/***** @ param t mode String, obtain the next function of pattern String backtracking */static void next (String t) {next = new int [t. length ()]; next [0] =-1; int j =-1; int I = 0; while (I <t. length ()-1) {if (j =-1 | t. charAt (I) = t. charAt (j) {I ++; j ++; if (t. charAt (I) = t. charAt (j) {next [I] = next [j];} else {next [I] = j ;}} else {j = next [j] ;}} /***** @ param s main String * @ param t mode String * @ param pos match from the pos subscript position of the Main String */static int match (String s, string t, int pos) {int I = pos; int j = 0; while (I <s. length () & j <t. length () {if (j =-1 | s. charAt (I) = t. charAt (j) {I ++; j ++;} else {j = next [j] ;}} if (j> t. length ()-1) {return I-j;} else {return-1 ;}} public static void main (String [] args) {String s = "aaaasad "; string t = "sa"; next (t); System. out. println (match (s, t, 0 ));}}