Advertisement
Guest User

Knuth Morris Pratt

a guest
Oct 22nd, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int * plotKMP(string p)
  5. {
  6.     int * pi = new int[p.length()+1];
  7.     pi[1] = 0;
  8.     int k = 0;
  9.     for(int q=2; q<=p.length(); q++){
  10.         //Condition to reset the k to init
  11.         while( k > 0 &&  p[k] != p[q-1] )
  12.             k = pi[k];
  13.         //If match is found, advance k(prefix length)
  14.         if( p[k] == p[q-1] )
  15.             k = k + 1;
  16.         //Write prefix length to pi table
  17.         pi[q] = k;
  18.  
  19.     }
  20.     return pi;
  21. }
  22.  
  23. void matchWithKMP(string text, string pattern){
  24.     int n = text.length();
  25.     int m = pattern.length();
  26.     bool notFound = 1;
  27.     int * pi = plotKMP(pattern);
  28.  
  29.     //Number of characters matched
  30.     int q = 0;
  31.  
  32.     for(int i=1; i<=n; i++)
  33.     {
  34.  
  35.         //Backtrack using pi table when match is not found
  36.         while( q>0 && pattern[q] != text[i-1] )
  37.             q = pi[q];
  38.  
  39.         //If match is found, advance q(next char is matched)
  40.         if( pattern[q] == text[i-1] )
  41.             q = q + 1;
  42.  
  43.         //If complete match is found:
  44.         if( q==m )
  45.         {
  46.             notFound = 0;
  47.             cout << "Pattern found with shift " << i-m << endl;
  48.             //Backtrack to find next match
  49.             q = pi[q];
  50.         }
  51.  
  52.     }
  53.     if(notFound)
  54.         cout << "Not found" << endl;
  55. }
  56.  
  57.  
  58.  
  59.  
  60. int main(){
  61.     string str1 = "xxxabcabcabcyyyabcabcabczzzabcabcabc";
  62.     string str2 = "abcabcabc";
  63.  
  64.     int * x = plotKMP(str2);
  65.  
  66.  
  67.  
  68.     matchWithKMP(str1, str2);
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement