Saturday, 10 May 2014

Boyer-Moore String Matching

You are supposed to implement Boyer Moore algorithm using bad character rule as explained in the lecture.

Input:
First line contains the text T. Second line contains the pattern P

Output:
Index of each occurrence of pattern P in small brackets as shown in the examples below.

Constraints:
1 <= length(P) <= length(T) < 100

#include<limits.h>
#include<string.h>
#include<stdio.h>
#define CHAR_SET_SIZE 256
void process(char *str, char *ptr, int R[CHAR_SET_SIZE])
{
int i,j;
int m=strlen(str);
int n=strlen(ptr);
for(i = 0; i < CHAR_SET_SIZE; i++)
{
R[i] = -1;
}
for(i = 0; i < m; i++)
{
for(j=0;j<n;j++)
{
if(ptr[j]==str[i])
R[j]=i;
}
}
}
void patternMatcher(char *T, char *P)
{
int R[CHAR_SET_SIZE],n,m,i,l,temp,count=0;
n=strlen(P);
m=strlen(T);
char A[m];
process(T,P,R);
for(l=0;l<n;l++)
{
A[l]=P[l];
}
temp=n-1;
for(i=0;i<m;i++)
{
while((T[temp]==A[temp])&&(temp>i-1))
temp--;
if(temp==i-1)
{
printf("(%d)",i);
count++;
}
for(l=i+1;l<n+i+1;l++)
{
A[l]=P[l-i-1];
}
temp=n+i;
}
if(count==0)
printf("-1");
}
int main()
{
char P[100],T[100];
gets(T);
gets(P);
patternMatcher(T,P);
return 0;
}

No comments: