-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
z.cpp
66 lines (62 loc) · 1.52 KB
/
z.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
#include <vector>
/**
* Function to fill in zvalues vector of ztext
*/
std::vector<size_t> fillZvalues(const std::string & ztext) {
size_t n = ztext.length();
std::vector<size_t> zvals(n, 0);
size_t L = 0, R = 0; // s[L..R] represent the prefix string.
for (size_t i = 1; i < n; ++i) {
if ( i > R ) {
L = R = i;
while( R < n && ztext[R-L] == ztext[R] ) {
++R;
}
zvals[i] = R-L;
--R;
} else {
size_t K = i - L;
if( zvals[K] < R-i+1 ) {
zvals[i] = zvals[K];
} else {
L = R = i;
while( R < n && ztext[R-L] == ztext[R] ) {
++R;
}
zvals[i] = R-L;
--R;
}
}
}
return zvals;
}
/**
* This function returns index of text where pattern matches using z algorithm
*/
std::vector<size_t> search( const std::string & text, const std::string & pattern ) {
std::string ztext = pattern + '$' + text;
std::vector<size_t> zvalues = fillZvalues(ztext);
std::vector<size_t> indices;
for ( size_t i = 1; i < zvalues.size(); ++i ) {
if (zvalues[i] == pattern.length()) {
indices.push_back(i - pattern.length() -1 );
}
}
return indices;
}
int main()
{
std::string text, pattern;
std::cout << "String searching using Z algorithm:\n";
std::cout << "Enter text:";
std::getline(std::cin, text);
std::cout << "Pattern :";
std::getline(std::cin, pattern);
std::vector<size_t> indices = search(text, pattern);
for (auto i : indices ) {
std::cout << pattern << " occurs in given text starting at index " << i << std::endl;
}
return 0;
}