diff --git a/C++/Algorithms/StingMatching/z_algorithm.cpp b/C++/Algorithms/StingMatching/z_algorithm.cpp new file mode 100644 index 000000000..8ac0d8296 --- /dev/null +++ b/C++/Algorithms/StingMatching/z_algorithm.cpp @@ -0,0 +1,90 @@ +// A C++ program that implements Z algorithm for pattern searching +#include +using namespace std; + +void getZarr(string str, int Z[]); + +// prints all occurrences of pattern in text using Z algo +void search(string text, string pattern) +{ + // Create concatenated string "P$T" + string concat = pattern + "$" + text; + int l = concat.length(); + + // Construct Z array + int Z[l]; + getZarr(concat, Z); + + // now looping through Z array for matching condition + for (int i = 0; i < l; ++i) + { + // if Z[i] (matched region) is equal to pattern + // length we got the pattern + if (Z[i] == pattern.length()) + cout << "Pattern found at index " + << i - pattern.length() -1 << endl; + } +} + +// Fills Z array for given string str[] +void getZarr(string str, int Z[]) +{ + int n = str.length(); + int L, R, k; + + // [L,R] make a window which matches with prefix of s + L = R = 0; + for (int i = 1; i < n; ++i) + { + // if i>R nothing matches so we will calculate. + // Z[i] using naive way. + if (i > R) + { + L = R = i; + + // R-L = 0 in starting, so it will start + // checking from 0'th index. For example, + // for "ababab" and i = 1, the value of R + // remains 0 and Z[i] becomes 0. For string + // "aaaaaa" and i = 1, Z[i] and R become 5 + while (R