forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Knutt_Morris_Prat.c
58 lines (52 loc) · 1.41 KB
/
Knutt_Morris_Prat.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
/*Knuth–Morris–Pratt string-searching algorithm
Searches for occurrences of a word W within a main text string S
*/
#include <stdio.h>
#include <string.h>
int Knutt_Morris_Prat(char[], char[]);
int main()
{
char string[20], matchcase[20];
printf("Enter string: ");
gets(string);
printf("Enter substring: ");
gets(matchcase);
Knutt_Morris_Prat(string, matchcase);
return 0;
}
int Knutt_Morris_Prat(char string[], char matchcase[])
{
int i, j = 0, index;
for (i = 0; i < strlen(string) - strlen(matchcase) + 1; i++)
{
index = i;
if (string[i] == matchcase[j]) /*Check if characters match*/
{
/*Continue checking until the characters match or the end of pattern string is reached*/
do {
i++;
j++;
} while (j != strlen(matchcase) && string[i] == matchcase[j]);
if (j == strlen(matchcase)) /*if j is equal to pattern length, pattern is found.*/
{
printf("Match found from position %d to %d.\n", index + 1, i);
return 0;
}
else /*if j is not equal to pattern length, move to next character and continue the same steps.*/
{
i = index + 1;
j = 0;
}
}
}
printf("No substring match found in the string.\n");
return 0;
}
/*
Time Complexity: O(n + m) - n is the length of string and m is the length of substring
Space Complexity: O(m) - m is the length of substring
Sample Output
Enter string: ABCABAABCABAC
Enter subsring: CAB
Match found from position 3 to 5.
*/