forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zalgorithm.c
72 lines (66 loc) · 1.12 KB
/
zalgorithm.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
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <string.h>
void getZ(char s[], int z[])
{
int n = strlen(s);
int left = 0, right = 0;
for (int i = 1; i < n; ++i)
{
if (i > right)
{
left = right = i;
while (right < n && s[right - left] == s[right])
right++;
z[i] = right - left;
right--;
}
else
{
int k = i - left;
if (z[k] < right - i + 1)
{
z[i] = z[k];
}
else
{
left = i;
while (right < n && s[right - left] == s[right])
right++;
z[i] = right - left;
right--;
}
}
}
}
int main()
{
char text[100], pattern[100];
printf("Enter the text: ");
scanf("%s", text);
printf("\nEnter the pattern: ");
scanf("%s", pattern);
int m = strlen(pattern);
strcat(pattern, "$");
strcat(pattern, text);
int n = strlen(pattern);
int z[n];
getZ(pattern, z);
for (int i = 0; i < n; ++i)
{
if (z[i] == m)
{
printf("\nPattern found at index %d", i - m - 1);
}
}
return 0;
}
/*
Time Complexity: O(length of text + length of pattern)
Input
Enter the text: AABACAAFGAABAABA
Enter the pattern: AABA
Output
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
*/