-
Notifications
You must be signed in to change notification settings - Fork 2
/
Zalgorithm.cpp
50 lines (47 loc) · 1.09 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
/*
@author Sukeesh
Z Algorithm
*/
ll Zarray[1000010];
void Z(string str){
memset(Zarray, 0, sizeof(Zarray));
ll k;
ll right, left;
left = 0;
right = 0;
for(k = 1 ; k < str.sz ; k ++){
if(k > right){
left = right = k;
while(right < str.sz && str[right] == str[right - left]){
right ++;
}
Zarray[k] = right - left;
right --;
}
else{
ll k1 = k - left;
if(Zarray[k1] < right - k + 1){
Zarray[k] = Zarray[k1];
}
else{
left = k;
while(right < str.sz && str[right] == str[right - left]){
right ++;
}
Zarray[k] = right - left;
right --;
}
}
}
}
void calculateZ(string needle, string haystack){
ll i;
string str = needle + "$" + haystack;
Z(str);
for(i = 0 ; i < str.sz; i ++){
if(Zarray[i] == needle.sz){
cout << i - needle.sz - 1 << endl;
}
}
cout << endl;
}