spider68

KMP algo

Oct 26th, 2020 (edited)
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. void findPattern(vector<int> &prefix,string txt){
  7.     int idx=0,i=1;
  8.     while(i<txt.length()){
  9.         if(txt[i]==txt[idx]){
  10.             prefix[i++]= ++idx;
  11.         }    
  12.         else{
  13.             if(idx==0)i++;
  14.             else idx=prefix[idx-1];
  15.         }
  16.     }
  17. }
  18.  
  19. void find(string str, string txt){
  20.     int m=str.length(),n=txt.length();
  21.    
  22.     vector<int>prefix(n);
  23.     findPattern(prefix,txt);
  24.     int id=0,i=0;
  25.     while(i<m){
  26.         if(txt[id]==str[i])id++,i++;
  27.         else{
  28.             if(id==0)i++;
  29.             else id=prefix[id-1];
  30.         }
  31.        
  32.         if(id==n){
  33.             cout<<i-id<<" ";
  34.             id=prefix[id-1];
  35.         }
  36.     }
  37. }
  38. int main()
  39. {
  40.    string str="batmanandrobinarebat";
  41.    string txt="bat";
  42.    find(str,txt);
  43.    return 0;
  44. }
Add Comment
Please, Sign In to add comment