-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringAlgos.cpp
More file actions
45 lines (42 loc) · 1.01 KB
/
StringAlgos.cpp
File metadata and controls
45 lines (42 loc) · 1.01 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
// z func gives length of max suffix starting at ith index which is equal to prefix
vector<int> z_function(string s) {
int n = (int) s.length();
vector<int> z(n);
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = min (r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}
return z;
}
// pi func used in KMP
void calcPrefSuf(string &s,vector<int> &prefsuf)
{
int n=s.length();
int i=0,j=1;
while(j<n and i<j)
{
if(s[i]==s[j])
{
prefsuf[j]=i+1;
i+=1;
j+=1;
}
else
{
if(i==0)
{
j+=1;
i=0;
}
else
{
i=prefsuf[i-1];
}
}
}
return;
}