forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zalgorithm.cpp
70 lines (65 loc) · 1.1 KB
/
zalgorithm.cpp
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
#include <bits/stdc++.h>
using namespace std;
void getZ(string s, int z[])
{
int n = s.size();
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()
{
string text, pattern;
cout << "Enter the text: ";
cin >> text;
cout << "Enter the pattern: ";
cin >> pattern;
string concat = pattern + "$" + text;
int n = concat.size();
int m = pattern.size();
int z[n];
getZ(concat, z);
for (int i = 0; i < n; ++i)
{
if (z[i] == m)
{
cout << "Pattern found at index " << i - m - 1 << "\n";
}
}
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
*/