-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZ-algorith.cpp
More file actions
46 lines (45 loc) · 1006 Bytes
/
Z-algorith.cpp
File metadata and controls
46 lines (45 loc) · 1006 Bytes
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
//Z algorithm is used for pattern matching
/* the algorithm gives for every index i in String S the maximum prefix starting from
i is equal to prefix of S
*/
#include <bits/stdc++.h>
using namespace std;
vector<int> ZAlgo(string s)
{
int n = s.size();
vector<int> z(n);
int l = 0, r = 0;
for (int i = 1; i < n; i++)
{
if (i > r)
{
l = r = i;
while (r < n && s[r - l] == s[r])
r++;
z[i] = r - l;
r--;
}
else
{
int k = i - l;
if (z[k] < r - i + 1) // equality is nonsense
z[i] = z[k];
else
{
l = i;
while (r < n && s[r - l] == s[r])
r++;
z[i] = r - l;
r--;
}
}
}
return z;
}
int main(){
string s;cin>>s;
vector<int>z=ZAlgo(s);
for(int i=0;i<s.size();i++){
cout<<z[i]<<" ";
}
}