-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzs_pattern_match.cpp
More file actions
54 lines (45 loc) · 1.13 KB
/
zs_pattern_match.cpp
File metadata and controls
54 lines (45 loc) · 1.13 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
#include<bits/stdc++.h>
using namespace std;
void z_match(string text, string pat);
void calc_z_array(string text, int z[]);
void z_match(string text, string pat){
string full_string = pat + '$' + text;
int n = full_string.length();
int z[n];
z[0]=0;
calc_z_array(full_string, z);
for(int i=0; i < n; i++) {
if (z[i] == pat.length())
cout << "pattern found at index " << i-pat.length()-1 << "\n";
}
}
void calc_z_array(string text, int z[]){
int n = text.length();
int l, r, k;
l = r = 0;
for (int i=0; i < n ; i++){
if(i > r){
l = r = i;
while (r < n && text[r-l] == text[r])
r++;
z[i] = r-l;
r--;
}else{
k = i-l;
if (z[k] < r-i+1){
z[i] = z[k];
}else{
l = i;
while (r < n && text[r-l] == text[r])
r++;
z[i] = r-l;
r--;
}
}
}
}
int main(){
std::ios_base::sync_with_stdio(false);
z_match("geeks for geeks for geek", "geeks");
return 0;
}