From 2788923d72d0ba14868993f22aee92c0b223a261 Mon Sep 17 00:00:00 2001 From: Avigyan Das Date: Sat, 12 Oct 2019 01:40:17 +0530 Subject: [PATCH] Z algorithm --- Algorithms/Z-algorithm/z-algorithm.cpp | 95 ++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Algorithms/Z-algorithm/z-algorithm.cpp diff --git a/Algorithms/Z-algorithm/z-algorithm.cpp b/Algorithms/Z-algorithm/z-algorithm.cpp new file mode 100644 index 00000000..7f28f9c5 --- /dev/null +++ b/Algorithms/Z-algorithm/z-algorithm.cpp @@ -0,0 +1,95 @@ +// C++ implementation of Z algorithm +// +// Author: Avigyan Das + + +// 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