lelouche29

KMP

Sep 26th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void computeLps(int lps[],string s2){
  5.     lps[0]=0;
  6.     int m=s2.length();
  7.     int len=0;
  8.     int i=1;
  9.     while(i<m){
  10.         //if character matches
  11.         if(s2[len]==s2[i]){
  12.             len++;
  13.             lps[i]=len;
  14.             i++;
  15.         }
  16.         else{
  17.             if(len!=0)
  18.                 len=lps[len-1];
  19.             else{
  20.                 lps[i]=0;
  21.                 i++;
  22.             }
  23.         }
  24.     }
  25. }
  26.  
  27. //function for string matching
  28. void kmp(string s1, string s2){
  29.     int n=s1.length();
  30.     int m=s2.length();
  31.  
  32.     int lps[m];
  33.     computeLps(lps,s2);
  34.  
  35.     int i=0; //index for string
  36.     int j=0; //index for matching string
  37.  
  38.     while(i<n){
  39.         //if character of pattern matched with character of string
  40.         if(s1[i]==s2[j]){
  41.             i++;
  42.             j++;
  43.         }
  44.         //pattern found in string
  45.         if(j==m){
  46.             cout<<"pattern found at index " << i-j<<endl;
  47.             j=lps[j-1];
  48.         }
  49.         //if not matched
  50.         else if(i<n && s1[i]!=s2[j]){
  51.             //decrease lps till the last matched char
  52.             if(j!=0)
  53.                 j=lps[j-1];
  54.             else    
  55.                 i++;
  56.         }
  57.     }
  58. }
  59.  
  60.  
  61. int main() {
  62.     string s1, s2;
  63.     cin>>s1>>s2;
  64.     // cout<<s1<<" "<<s2;
  65.     kmp(s1,s2);
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment