KMP algorithm public class kmptest{//method: Gets the pattern string at the parent string position public static int Getindexof (String s,string m) {if (S==nul l| | m==null| | M.length () <1| |
S.length () <m.length ()) {return-1; } char[]ss=s.tochararray (); Main string array char[]ms=m.tochararray ();
substring string to array int si=0;
int mi=0;
Int[]next=getnextarray (MS);
while (si<ss.length&&mi<ms.length) {if (Ss[si]==ms[mi]) {si++;
mi++;
}else if (next[mi]==-1) {si++;
}else{Mi=next[mi];
} return mi==ms.length?si-mi:-1; //Get the next array of pattern strings public static Int[]getnextarray (CHAR[]MS) {if (ms.length==1) {return new int[]{-1
};
} int[]next=new Int[ms.length];
Next[0]=-1;
next[1]=0;
int pos=2;
int cn=0;
while (pos<ms.length) {if (MS[POS-1]==MS[CN]) { NEXT[POS++]=++CN;
}else if (cn>0) {CN=NEXT[CN];
}else{next[pos++]=0;
} return to Next;
public static void Main (String[]args) {//system.out.println ("Hello");
String s= "ABCDEFGH";
String m= "FGH";
String s1= "ABCDEFGH";
String m1= "FGX";
System.out.println (Getindexof (s,m));
System.out.println (Getindexof (S1,M1)); }
}