im trying to implement the kmp algorithm for fast string matching, im fairly new at programming so im having some trouble with syntax, i got the pseudocode from my text book
Code:
int prefix(const char *p)
{
int m = strlen(p);
int *a = new int[m];
a[1] = 0;
int k = 0;
for(int q=2;q<m;q++)
{
while(k>0 && p[k+1]!=p[q]){
k = a[k];
}
if(p[k+1]==p[q]){
k=k+1;}
a[q] = k;
}
return a;
}
int find_string(char *s, char *t)
{
int a = prefix(t);
int q = 0;
for(int i=1;i<strlen(s);i++)
{
while(q>0 && t[q+1]!=s[i]){
q = a[q];
}
if(t[q+1]==s[i]){q=q+1;}
if(q==strlen(t)){
return i-strlen(t);
q = a[q];
}
}
return -1;
}
//test code
int main(void)
{
char sequence[100001];
char pattern[1000];
int i, j;
for(i=0; i<100000; i++)
sequence[i] = 'a';
sequence[100000]='\0';
for(i=0; i<4000; i++)
{ j = rand()%100000;
sequence[j]='b';
}
for(j=0; j< 1000; j++)
pattern[j] = sequence[POSITION+j];
pattern[1000] = '\0';
if(find_string(sequence, pattern) == POSITION )
printf("accepted\n");
else
printf("needs check?\n");
}
Comment