Advertisement
SuitNdtie

Ctrl F 2 KMP

May 10th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. int main()
  4. {
  5.     int n,m;
  6.     scanf("%d %d",&n,&m);
  7.     char str1[n+1];
  8.     char str2[m+1];
  9.     scanf(" %s %s",str1,str2);
  10.    
  11.     int LPS[m+1];
  12.     LPS[0] = 0;
  13.     for(int i = 1 , j = 0 ; i < m ; ){
  14.         if(str2[i] == str2[j]){
  15.             LPS[i] = j + 1;
  16.             i ++ ; j ++;
  17.         }
  18.         else if(j > 0){
  19.             j = LPS[j-1];
  20.         }
  21.         else{
  22.             LPS[i] = 0;
  23.             i ++;
  24.         }
  25.     }
  26. //  printf("Test LPS : ");for(int i = 0 ; i < m ; i ++ )printf("%d ",LPS[i]);printf("\n");
  27.    
  28.     int cnt = 0;
  29.     for(int i = 0 , j = 0 ; i < n ; ){
  30.         if(str1[i] == str2[j]){
  31.             i ++ ; j ++;
  32.             if(j == m){ //match
  33.                 cnt++;
  34.                 j = LPS[j-1];
  35.             }
  36.         }
  37.         else if(j > 0){
  38.             j = LPS[j-1];
  39.         }
  40.         else{
  41.             i ++;
  42.         }
  43.     }
  44.     printf("%d",cnt);
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement