Given a main string (in the case of s) and a pattern string (substituted by P), we need to find out where p appears in S, which is the pattern matching problem of the string. Knuth-morris-pratt algorithm (KMP) is one of the most common algorithms for solving this problem, and this algorithm is based on Gartner (Donald Ervin Knuth) and Vaughn Pratt conceived in 1974, the same year James · H. Morris also designed the algorithm independently, and eventually the trio were published jointly in 1977.
String matching problem public class stringmatch{//Solution one: Violent match public static int IsMatch (String s,string p) {int i=0;
int j=0;
Char[]s1=s.tochararray ()//Record the original string Char[]p1=p.tochararray ();//Record mode string while (I<s1.length&&j<p1.length) {
if (S1[i]==p1[j])//If equal, move one {i++;
j + +;
else//The original string is moved one bit, the pattern string from the beginning match {i=i-j+1;
j=0;
}//Termination condition if (j==p1.length) return i-j;
} return-1;
//Solution two KMP algorithm//Get jump array Next public static Int[]next (char[]p) {int p_len=p.length; Int[]next=new int[p_len+1];//initialization length of +1 int i=0;
subscript int j=-1 of p;
Next[0]=-1;
System.out.println (P_len); while (I<p_len) {if (j==-1| |
P[i]==p[j]) {i++;
j + +;
Next[i]=j;
}else {j=next[j];//from the matching value subscript start to return to next;
}/** s indicates that the original string p represents the mode string/public static int KMP (string s,string p) {char []ss=s.tochararray ();
char []pp=p.tochararray (); Int[]next=next (PP);//get jump array int i=0; The original string subscript int j=0;
Pattern string subscript int s_len=ss.length;
int p_len=pp.length; while (I<s_len&&j<p_len) {if (j==-1| |
Ss[i]==pp[j]) {i++;
j + +; }else {j=next[j];//Current character match failed, make jump} if (J==p_len) {return I
J
}} return-1;
public static void Main (string []args) {string s= "ABCDEF";
String p= "DE";
System.out.println (IsMatch (s,p));
System.out.println (KMP (s,p));
}
}