Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. ///KMP pattern searching in a string
  2. ///6-Apr-2020
  3.  
  4. #include <iostream>
  5.  
  6. int main() {
  7.     char text[] = "abazaababaababababc";
  8.     char pattern[] = "ababc";
  9.     int pat_len = strlen(pattern);
  10.     int txt_len = strlen(text);
  11.     int i, j=0;
  12.     int fail_vector[5];
  13.  
  14. /// Computing the fail_function
  15. /// fail function will have under the letter the longest suffix that is also a preffix of the current substring
  16. ///for example fail_vector[ababc]={-1,0,1,2,0}  
  17.         int max_suf = 0;
  18.         fail_vector[0] = -1;
  19.         i = 1;
  20.         while (i < pat_len) {
  21.             if (pattern[i] == pattern[max_suf]) {
  22.                 max_suf++;
  23.                 fail_vector[i] = max_suf;
  24.                 i++;
  25.             }
  26.             else
  27.             {
  28.                 if (max_suf != 0) {
  29.                     max_suf = fail_vector[max_suf - 1];
  30.                     fail_vector[i] = 0;
  31.                 }
  32.                 else
  33.                 {
  34.                     fail_vector[i] = 0;
  35.                     i++;
  36.                 }
  37.             }
  38.         }
  39. ///end of fail_function
  40.  
  41. ///KMP search
  42.     i = j = 0;
  43.     while (i < txt_len) {
  44.         if (pattern[j] = text[i]) {
  45.             j++;
  46.             i++;
  47.         }
  48.         if (j == pat_len) {
  49.             std::cout << "First pattern found at index  "  << i - j;
  50.             j = fail_vector[j - 1];
  51.             return 0;
  52.         }
  53.         else if (i < txt_len && pattern[j] != text[i]) {
  54.             if (j != 0)
  55.                 j = fail_vector[j - 1];
  56.             else
  57.                 i++;
  58.         }
  59.     }
  60. ///end of KMP search
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement