Advertisement
keverman

Knuth-Morris-Pratt algorithm

May 10th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. int KMP(std::string &pattern, std::string &word)
  2. {
  3.     // Compute the partial match table
  4.     std::vector<int> part_match(pattern.size());
  5.     part_match[0] = 0;
  6.  
  7.     for(int i = 1; i < pattern.size(); i++)
  8.     {
  9.         // Start with the previous partial match
  10.         part_match[i] = part_match[i - 1];
  11.  
  12.         // Jump back until a partial match at the current position is found
  13.         while(part_match[i] > 0 && pattern[i] != pattern[part_match[i]])
  14.             part_match[i] = part_match[part_match[i] - 1];
  15.  
  16.         // Increment the partial match if it's non-zero
  17.         if(pattern[i] == pattern[part_match[i]])
  18.             part_match[i]++;
  19.     }
  20.  
  21.     // Find a match
  22.     for(int i = 0, j = 0; i < word.size(); i++)
  23.     {
  24.         // Jump back until a partial match at the current position is found
  25.         while(j > 0 && word[i] != pattern[j])
  26.             j = part_match[j - 1];
  27.  
  28.         // If it's a full match, return its position
  29.         if(word[i] == pattern[j] && ++j == pattern.size())
  30.             return i - j + 1;
  31.     }
  32.  
  33.     // No full matches found
  34.     return -1;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement