Advertisement
LunaeStellsr

KMP

Nov 7th, 2018
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <string.h>
  4.  
  5. using namespace std;
  6.  
  7. // Implement the failure function
  8. void failure_function(const char* pat, int failure[]){
  9.     string str = pat;
  10.     for(int i = 1, j = failure[0] = -1; i<str.length();++i){
  11.         while(j >= 0 && str[j+1] != str[i]){
  12.             j = failure[j];
  13.         }
  14.         if(str[j+1] == str[i]){j++;}
  15.         failure[i] = j;
  16.     }
  17.     for(int i=0;i<str.length();++i){cout << failure[i] << ' ';}
  18.     cout << '\n';
  19. }
  20.  
  21. // Return the position of the first occurrence of pat in s
  22. int pmatch(const char *str, const char *pat,int failure[]){
  23.     string a = str, b = pat;
  24.     if(a.length() < b.length())return -1;
  25.     for(int i=0, j=-1;i<a.length();i++){
  26.         while (j >= 0 && b[j+1] != a[i]){
  27.             j = failure[j];
  28.         }
  29.         if(b[j+1] == a[i])j++;
  30.  
  31.         // pattern matched
  32.         if(j == b.length() - 1){
  33.             int pos = i - b.length() + 1;
  34.             return pos;
  35.         }
  36.     }
  37.     return -1;
  38. }
  39.  
  40. // Do not modify the main function
  41. int main(){
  42.     char pat[100], s[500]; int f[100];
  43.     int i, pos, first_char, count;
  44.     scanf("%s",s); scanf("%s", pat);
  45.     failure_function(s, f);
  46.     failure_function(pat,f);
  47.     pos = 0; count = 0;
  48.  
  49.     do{
  50.         first_char = pmatch(s + pos, pat, f);
  51.         if(first_char != -1) {
  52.             count++;
  53.             pos = pos + first_char + 1;
  54.         }
  55.         else{break;}
  56.     }while(1);
  57.     printf("%d\n",count);
  58.     return 0;
  59. }
  60. /*
  61. abcabcabcaabcdabcde
  62. abc
  63. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement