KMP algorithm is a classic algorithm, online many great gods have given a very detailed description, this no longer repeat.
The following is the implementation of the KMP algorithm, which uses a policy pattern.
Public interface Inextbuilder {public
abstract int[] Build (char[] p);
Implementation of recursive thought of writing Inextbuilder interface
Package COM.SOFT.KMP;
public class Recurnextbuilder implements Inextbuilder {
@Override public
int[] Build (char[] p) {
int[] Next=new Int[p.length];
int k=-1;
Next[0]=-1;
Traversal 0->p.length-1 for
(int i=0;i<p.length-1;i++) {
if k==-1| | P[i]==p[k]) {
k++;
next[i+1]=k;
} else{
k=next[k];
}
return next;
}
Non-recursive implementation of writing Inextbuilder interface
Package COM.SOFT.KMP;
public class Straitnextbuilder implements Inextbuilder {
@Override public
int[] Build (char[) p) {
// Do it yourself, measure your level return
null;
}
Finally, write KMP class and test
Package COM.SOFT.KMP;
public class KMP {
private inextbuilder nextbuilder;
Public KMP (Inextbuilder nextbuilder) {
this.nextbuilder=nextbuilder;
}
Public KMP () {
this.nextbuilder=new recurnextbuilder ();
}
public int Kmpmatch (String s,string p) {
char[] Pa=p.tochararray ();
Char[] Sa=s.tochararray ();
Int[] Next=this.nextbuilder.build (PA);
for (int i=0,j=0;i<sa.length;) {
if (J==-1 | | Sa[i]==pa[j]) {
i++;j++;
} else{
j=next[j];
}
if (j==pa.length) {return
i-j
}}
return-1;
}
public static void Main (string[] args) {
KMP kmp=new KMP ();
System.out.println (KMP. Kmpmatch ("Helllo", "Llo"));
}
Run Result: 3