Advertisement
mickypinata

GRD3-T08: String Search

Nov 24th, 2020
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long lli;
  5.  
  6. const int N = 1e6;
  7.  
  8. int idxLPP[N + 1];
  9. char trStr[N + 1], ptStr[N + 1];
  10. int lenTr, lenPt;
  11.  
  12. int main(){
  13.  
  14.     scanf("%d %d", &lenTr, &lenPt);
  15.     scanf(" %[^\n]", trStr);
  16.     scanf(" %[^\n]", ptStr);
  17.  
  18.     idxLPP[0] = 0;
  19.     for(int i = 1; i < lenPt; ++i){
  20.         int idx = idxLPP[i - 1];
  21.         do {
  22.             if(ptStr[idx] == ptStr[i]){
  23.                 idxLPP[i] = idxLPP[idx] + 1;
  24.                 break;
  25.             }
  26.             idx = idxLPP[idx - 1];
  27.         } while (idx > 0);
  28.     }
  29.  
  30.     int idxT = 0;
  31.     int idxP = 0;
  32.     while(idxT < lenTr){
  33.         if(trStr[idxT] == ptStr[idxP]){
  34.             ++idxT;
  35.             ++idxP;
  36.             if(idxP == lenPt){
  37.                 cout << idxT - idxP << "\n";
  38.                 idxP = idxLPP[idxP - 1];
  39.             }
  40.         } else if(idxP == 0){
  41.             ++idxT;
  42.         } else {
  43.             idxP = idxLPP[idxP - 1];
  44.         }
  45.     }
  46.  
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement