C language using BF-KMP algorithm instance _c language

Source: Internet
Author: User

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 ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.