z algorithm Algorithm
The Z algorithm, also known as the Z-function algorithm, is a linear time complexity algorithm used for string matching and pattern searching within a given text. This powerful technique is particularly effective in solving problems related to string processing, as it is able to identify all occurrences of a pattern within a text string in a highly efficient manner. The fundamental concept behind the Z algorithm is the construction of a Z-array or Z-table, which stores the length of the longest common prefix between the main string and its substrings, helping to quickly identify matches between the pattern and the text.
In essence, the Z algorithm preprocesses the given pattern and text by concatenating them with a unique separator, which is not a part of the input strings. Following this, it calculates the Z-values for each character in the concatenated string. These Z-values represent the longest common prefix lengths between the main string and its corresponding substrings. By iterating through the Z-array, the algorithm can efficiently identify all positions where the pattern occurs in the text, as the Z-values at these positions will be equal to the length of the pattern. This preprocessing step enables the Z algorithm to perform pattern searching in linear time, making it a highly effective and practical solution for various string matching problems.
/**
* C++ Program to Implement Z-Algorithm
*/
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
bool zAlgorithm(string pattern, string target)
{
string s = pattern + '$' + target;
int n = s.length();
vector<int> z(n, 0);
int goal = pattern.length();
int r = 0, l = 0, i;
for (int k = 1; k < n; k++)
{
if (k > r)
{
for (i = k; i < n && s[i] == s[i - k]; i++)
;
if (i > k)
{
z[k] = i - k;
l = k;
r = i - 1;
}
}
else
{
int kt = k - l, b = r - k + 1;
if (z[kt] > b)
{
for (i = r + 1; i < n && s[i] == s[i - k]; i++)
;
z[k] = i - k;
l = k;
r = i - 1;
}
}
if (z[k] == goal)
return true;
}
return false;
}
int main()
{
string tar = "This is a sample Testcase";
string pat = "case";
if (zAlgorithm(pat, tar))
{
cout << "'" << pat << "' found in string '" << tar << "'" << endl;
}
else
{
cout << "'" << pat << "' not found in string '" << tar << "'" << endl;
}
pat = "Kavya";
if (zAlgorithm(pat, tar))
{
cout << "'" << pat << "' found in string '" << tar << "'" << endl;
}
else
{
cout << "'" << pat << "' not found in string '" << tar << "'" << endl;
}
return 0;
}