CJamie

boyermoore

May 12th, 2022
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void search(string word, string pattern)
  5. {
  6. const int n = word.size();
  7. const int m = pattern.size();
  8.  
  9. vector<int> badMatch(52, -1);
  10. for (int i = 0; i < m; i++)
  11. badMatch[pattern[i] - 'a'] = i;
  12.  
  13. int shift = 0;
  14. while (shift <= (n - m))
  15. {
  16. int j = m - 1;
  17.  
  18. while (j >= 0 && pattern[j] == word[shift + j])
  19. j--;
  20.  
  21. if (j < 0)
  22. {
  23. cout << "\nfound at: " << shift << endl;
  24. shift += (shift + m < n) ? m - badMatch[word[shift + m]] : 1;
  25. }
  26.  
  27. else
  28. shift += max(1, j - badMatch[word[shift + j]]);
  29. }
  30. }
  31.  
  32. int main()
  33. {
  34. string word = "WELCOME TO THAPAR";
  35. string pattern = "THAPAR";
  36. search(word, pattern);
  37. return 0;
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment