Z-Algorithm in C++
Posted by Superadmin on August 08 2022 05:33:05

Z-Algorithm in C++

 

 

This C++ Program demonstrates the implementation of Z-Algorithm.

 

Here is source code of the C++ Program to implement Z-Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Implement Z-Algorithm
  3.  */
  4. #include <iostream>
  5. #include <cstring>
  6. #include <vector>
  7. using namespace std;
  8. bool zAlgorithm(string pattern, string target)
  9. {
  10.     string s = pattern + '$' + target;
  11.     int n = s.length();
  12.     vector<int> z(n, 0);
  13.     int goal = pattern.length();
  14.     int r = 0, l = 0, i;
  15.     for (int k = 1;  k < n; k++)
  16.     {
  17.         if (k > r)
  18.         {
  19.             for (i = k; i < n && s[i] == s[i - k]; i++);
  20.             if (i > k)
  21.             {
  22.                 z[k] = i - k;
  23.                 l = k;
  24.                 r = i - 1;
  25.             }
  26.         }
  27.         else
  28.         {
  29.             int kt = k - l, b = r - k + 1;
  30.             if (z[kt] > b)
  31.             {
  32.                 for (i = r + 1; i < n && s[i] == s[i - k]; i++);
  33.                 z[k] = i - k;
  34.                 l = k;
  35.                 r = i - 1;
  36.             }
  37.         }
  38.         if (z[k] == goal)
  39.             return true;
  40.     }
  41.     return false;
  42. }
  43.  
  44. int main()
  45. {
  46.     string tar = "san and linux training";
  47.     string pat = "lin";
  48.     if (zAlgorithm(pat, tar))
  49.         cout<<"'"<<pat<<"' found in string '"<<tar<<"'"<<endl;
  50.     else
  51.         cout<<"'"<<pat<<"' not found in string '"<<tar<<"'"<<endl;
  52.     pat = "sanfoundry";
  53.     if (zAlgorithm(pat, tar))
  54.         cout<<"'"<<pat<<"' found in string '"<<tar<<"'"<<endl;
  55.     else
  56.         cout<<"'"<<pat<<"' not found in string '"<<tar<<"'"<<endl;
  57.     return 0;
  58. }

 

$ g++ z-algorithm.cpp
$ a.out
 
'lin' found in string 'san and linux training'
'sanfoundry' not found in string 'san and linux training'
 
------------------
(program exited with code: 1)
Press return to continue