Friday, 24 November 2017

C++ Program to Implement Z-Algorithm


Code:

#include     iostream
#include     cstring
#include     vector
using namespace std;
bool zAlgorithm(string pattern, string target)
{
    string s = pattern + '$' + target;
    int n = s.length();
    vector 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 = "san and linux training";
    string pat = "lin";
    if (zAlgorithm(pat, tar))
        cout<<"'"<
    else
        cout<<"'"<
    pat = "sanfoundry";
    if (zAlgorithm(pat, tar))
        cout<<"'"<
    else
        cout<<"'"<
    return 0;
}


Output:

'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



More C++ Programs:















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...