forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Z_Algorithm.cpp
76 lines (58 loc) · 1.32 KB
/
Z_Algorithm.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
71
72
73
74
75
76
#include <iostream>
using namespace std;
void getZarr(string str, int Z[])
{
int n = str.length(), Left = 0, Right = 0, k;
for(int i = 1; i < n; i++)
{
if(i > Right)
{
Left = Right = i;
while(Right < n && str[Right - Left] == str[Right])
Right++;
Z[i] = Right - Left;
Right--;
}
else
{
k = i - Left;
if(Z[k] < Right - i + 1)
Z[i] = Z[k];
else
{
Left = i;
while(Right < n && str[Right - Left] == str[Right])
Right++;
Z[i] = Right - Left;
Right--;
}
}
}
}
void search(string text, string pattern)
{
string concat = pattern + "$" + text;
int size = concat.length();
int *Z = new int[size];
getZarr(concat, Z);
for(int i = 0; i < size; i++)
if(Z[i] == pattern.length())
cout << "Pattern found at " << i - pattern.length() << endl;
delete[] Z;
}
int main()
{
string text = "namanchamanbomanamansanam";
string pattern = "aman";
search(text, pattern);
return 0;
}
/*
Input:
namanchamanbomanamansanam
aman
Output:
Pattern found at 2
Pattern found at 8
Pattern found at 17
*/