KMP

KMP Pattern matching algorithm

String: ababababcd   pattern: ababcd

For pattern matching using Naïve method what we do is to compare first character from of both string , if it matches then we move ahead and look for all other characters, if it doesn’t match we move index in main string back to the original character and start the process again. This takes a bit of time as we are recomparing all the charactes. To avoid that we can calculate the shift of pattern at every index so we don’t have to shift the pattern to start, we can shift to last successfully compared character.

We basically check how many times the prefix of pattern starting from start is repeating inside the pattern. We compare from start if we find a difference we reset or else we increment.

For this we create pi of pattern of  length  m:

For(int I = 0 ,num=0;i<m;i++){

            If(i!=0 && pattenr[num]==pattern[i]){

                        Num++;

                        Pi[i]=num;

                        i++;

            }

            Else{

                        If(num>0){

                                    num = Pi[num-1];

                        }

                        Else{

                                    P[i]=0;

                                    I++;                            

                        }

                       

            }

}

So according to this my pi for pattern will be:

Abababcd

00121200

 

Now for for each index in main string s  of length n

We compare main String and pattern j

If(String[i]==pattern[j]){

            I++;

            J++;

            If(j==m){

                        Pattern found;

            }

}else{

            If(j>=0){

                        J = pi[j-1]; //we do not reset to 0 but to last successful matched                        index

            }

            Else{

                        I++;

            }

}

Comments

Popular posts from this blog

LeetCode 3Sum

New start Day 2 (1/10/2020) codeforces 492B Vanya and Lantern

Heap (min)