Directly on the code
Copy Code code as follows:
#define _crt_secure_no_warnings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 255//define maximum length of string
typedef unsigned char sstring[max_size];//array first save length
BF
int Bfmatch (char *s,char *p)
{
int i,j;
i=0;
while (I < strlen (s))
{
j=0;
while (S[i]==p[j]&&j < strlen (p))
{
i++;
j + +;
}
if (J==strlen (p))
Return I-strlen (P);
i=i-j+1; Pointer I backtracking
}
return-1;
}
Getnetx
void GetNext (char *p,int *next)
{
int j,k;
Next[0]=-1;
j=0;
K=-1;
while (J < strlen (p)-1)
{
if (k==-1| | P[J]==P[K])///matching case, P[j]==p[k]
{
j + +;
k++;
Next[j]=k;
}
Else
{//p[j]!=p[k]
K=NEXT[K];
}
}
}
Kmp
int Kmpmatch (char *s,char *p)
{
int next[100];
int i,j;
i=0;
j=0;
GetNext (P,next);
while (I < strlen (s))
{
if (j==-1| | S[I]==P[J])
{
i++;
j + +;
}
Else
{
J=NEXT[J]; Eliminates the backtracking of pointer I
}
if (J==strlen (p))
{
Return I-strlen (P);
}
}
return-1;
}
int main ()
{
int A, B;
Char S[max_size], p[max_size];
printf ("Please enter a pattern string:");
scanf ("%s", &s);
printf ("Please enter substring:");
scanf ("%s", &p);
A = Bfmatch (S, p);
B = Kmpmatch (S, p);
If (a!=-1)
{
printf ("Using the BF algorithm:%d\n", a);
}
Else
{
printf ("Unmatched \ n");
}
if (b!=-1)
{
printf ("Using KMP algorithm:%d\n", a);
}
Else
{
printf ("Unmatched \ n");
}
System ("pause");
}
Results
Copy Code code as follows:
Please enter a pattern string: lalalalalaaaa
Please enter a substring: LALAA
Using the BF algorithm: 6
Using the KMP algorithm: 6
Please press any key to continue ...