Advertisement
Josif_tepe

Untitled

Dec 24th, 2023
675
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. const int maxn = 1e5 + 10;
  4. int lps[maxn];
  5. void preprocess_lps(string pattern) {
  6.     int j = 0, i = 1;
  7.     lps[0] = 0;
  8.    
  9.     while(i < (int) pattern.size()) {
  10.         if(pattern[i] == pattern[j]) {
  11.             lps[i] = j + 1;
  12.             j++;
  13.             i++;
  14.         }
  15.         else {
  16.             if(j != 0) {
  17.                 j = lps[j - 1];
  18.             }
  19.             else {
  20.                 lps[i] = 0;
  21.                 i++;
  22.             }
  23.         }
  24.     }
  25. }
  26. void kmp(string text, string pattern) {
  27.     int n = (int) text.size();
  28.     int m = (int) pattern.size();
  29.     preprocess_lps(pattern);
  30.     int i = 0, j = 0;
  31.     while(n - i >= m - j) {
  32.         if(text[i] == pattern[j]) {
  33.             i++;
  34.             j++;
  35.         }
  36.         if(j == m) {
  37.             cout << "found at index: " << i - j << endl;
  38.             j = lps[j - 1];
  39.         }
  40.         else if(i < n and text[i] != pattern[j]) {
  41.             if(j != 0) {
  42.                 j = lps[j - 1];
  43.             }
  44.             else {
  45.                 i++;
  46.             }
  47.         }
  48.     }
  49. }
  50.  
  51. int main() {
  52.    
  53.     kmp("abxabcabcaby", "abcaby");
  54.    return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement