-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZ_Algorithm_Pattern_Search.cpp
More file actions
92 lines (58 loc) · 1.52 KB
/
Z_Algorithm_Pattern_Search.cpp
File metadata and controls
92 lines (58 loc) · 1.52 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
85
86
87
88
89
90
91
92
#include <iostream>
#include <string>
#include <vector>
#include <time.h>
#include <cmath>
using namespace std;
void ZAlgorithmPatternSearch(string text, string pattern){
string z = pattern + "$"+ text;
int m = z.length();
vector<int> z_array(m,0);
int l = 0;
int r = 0;
int k = 0;
clock_t start = clock();
for(int i = 1; i < m; i++){
if(i <= r){
k = i - l;
z_array[i] = min((r - i + 1),z_array[k]);
}
while(i + z_array[i] < m && z[z_array[i]] == z[i + z_array[i]]){
z_array[i]++;
}
if(i + z_array[i] - 1 > r){
l = i;
r = i + z_array[i] - 1;
}
}
vector<int> match_pos;
int n = pattern.length();
for (int i = n + 1; i < z_array.size(); i++) {
if (z_array[i] == n){
match_pos.push_back(i - n - 1);
}
}
clock_t end = clock();
double elapsed = double(end - start) / CLOCKS_PER_SEC;
cout << "Elapsed time: " << elapsed << " seconds." << std::endl;
if(match_pos.size() > 0){
cout << "Matches found at Positions: ";
for(int &i: match_pos){
cout << i+1 << " ";
}
cout << endl;
}
else{
cout << "No match found." << endl;
}
}
int main(){
string text;
string pattern;
cout << "Enter Your Text: ";
getline(cin,text);
cout << "Enter Your Pattern: ";
getline(cin,pattern);
ZAlgorithmPatternSearch(text,pattern);
return 0;
}