Blog Archive

Longest Prefix Suffix (KMP Algorithm)

 Longest Prefix Suffix (KMP Algo)

Given a string of characters, find the length of the longest proper prefix which is also a proper suffix.

Example:

Input: s = "abab"
Output: 2
Explanation: "ab" is the longest proper 
prefix and suffix.

Steps:

Make a array to store length of the matching prefix and Suffix  in order that the last entry will have the matched prefix and suffix length.




Solution:

int lps(string s)
{
    vector<intA(s.size(), 0);
    int j = 0i = 1;

    while (i < s.size())
    {
        if (s[i] == s[j])
        {
            A[i] = j + 1;
            j++;
            i++;
        }
        else
        {
            if (j == 0)
                i++;
            else
                j = A[j - 1];
        }
    }

    return A.back();
    // back() return last entry of the vector
}

data structures and algorithm- string data structure


Thank You.

No comments:

Post a Comment

Recent Post

Sort an array of 0s, 1s and 2s

  Sort an array of 0s, 1s and 2s- Data Structures   Sort an array of 0s, 1s and 2s- Data Structures Given an array of size N containing onl...