Advertisement
akashtadwai

KMP-Prefix-Function

Aug 22nd, 2021
1,252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define all(x) x.begin(),x.end()
  4.  
  5. vector<int> prefix_function(string &s){
  6.     int n=s.size();
  7.     vector<int>pi(n);
  8.     for(int i=1;i<n;i++){
  9.         int j=pi[i-1];
  10.         while(j and s[i]!=s[j]) j=pi[j-1];
  11.         if(s[i]==s[j]) j++;
  12.         pi[i]=j;
  13.     }
  14.     return pi;
  15. }
  16. void KMP(string pat, string text){
  17. int n=pat.size();
  18.  pat+='#';
  19.  pat+=text;
  20.   vector<int>pref = prefix_function(pat);
  21.   for(int i=0;i<(int)pref.size();i++){
  22.       if(pref[i]==n){
  23.           cout<<i-2*n<<" ";
  24.       }
  25.   }
  26. }
  27. void init() {
  28.  string pat,text;
  29.  cin>>text>>pat;
  30.  KMP(pat,text);
  31. }
  32. int32_t main() {
  33.   init();
  34.   return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement