-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnhay.cpp
More file actions
84 lines (75 loc) · 1.36 KB
/
nhay.cpp
File metadata and controls
84 lines (75 loc) · 1.36 KB
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
77
78
79
80
81
82
83
84
#include<iostream>
#include<vector>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;
// Z-Algorithm for Pattern Matching
// O(n+m)
inline vector<int> calculateZ(string inp)
{
int len = inp.length();
vector<int> Z(len);
int left = 0;
int right = 0;
for(int k = 1; k < len; k++)
{
if(k > right)
{
left = right = k;
while(right < len && inp[right] == inp[right-left])
{
right++;
}
Z[k] = right - left;
right--;
}
else
{
int k1 = k - left;
// inside the Z-Box
if(Z[k1] < right-k+1)
{
Z[k] = Z[k1];
//if the value is inside the Z-box then copy it
}
else
{
// otherwise do more comparisons
left = k;
while(right < len && inp[right] == inp[right-left])
{
right++;
}
Z[k] = right-left;
right--;
}
}
}
return Z;
// Z[i] denotes the length of the longest substring starting from i which is also the prefix of the string.
}
int main()
{
int needle_len;
while(scanf("%d",&needle_len)!= EOF)
{
string needle,hay;
cin >> needle >> hay;
string new_str = needle + "$" + hay;
vector<int> zz = calculateZ(new_str);
/* for(int i = 0; i < zz.size(); i++)
cout << zz[i] << " " ;
cout << "\n";
*/
for(int i = 0; i < zz.size(); i++)
{
if(zz[i] == needle_len)
{
cout << i-needle_len-1 << "\n";
}
}
cout << "\n";
}
return 0;
}