-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp_3 (1).c
59 lines (54 loc) · 917 Bytes
/
kmp_3 (1).c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<stdio.h>
#include<string.h>
int failure[20];
void fail(char *pat)
{
int i,j;
int n=strlen(pat);
failure[0]=-1;
for(j=1;j<n;j++)
{
i=failure[j-1];
while((pat[j]!=pat[i+1])&&(i>0))
i=failure[i];
if(pat[j]==pat[i+1])
failure[j]=i+1;
else
failure[j]=-1;
}
}
int match(char *string, char *pat)
{
int i=0,j=0;
int lens=strlen(string);
int lenp=strlen(pat);
while(i<lens&&j<lenp)
{
if(string[i]==pat[j])
{
i++;
j++;
}
else if(j==0)
i++;
else
j=failure[j-1]+1;
}
return((j==lenp)?(i-lenp):-1);
}
int main()
{
int i;
char str[30],pat[20];
printf("\nEnter a string\n");
scanf("%s",str);
printf("\nEnter a substring\n");
scanf("%s",pat);
fail(pat);
i=match(str,pat);
if(i==-1)
printf("\nPattern %s Not found", pat);
else
printf("\nPattern %s Founded at position %d",pat,i+1);
return 0;
}