Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. #include <string>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class HashPatternSearcher {
  6. private:
  7. string _pat, _txt;
  8. const int _ALPHABET_SIZE = 'Z' - 'A' + 1;
  9. long long _mod; char _initChar;
  10. vector<long long> _powVec, _hashBaseText;
  11. long long _hashBasePat;
  12. void buildHashBase(const bool rebuildHashPatBase = false) {
  13. long txtLen = (this->_txt).length();
  14. (this->_powVec).push_back(1);
  15. for (long i = 1; i <= txtLen; ++i) (this->_powVec).push_back(((this->_powVec).at(i-1) * this->_ALPHABET_SIZE) % this->_mod);
  16. (this->_hashBaseText).push_back(0);
  17. for (long i = 1; i <= txtLen; ++i) (this->_hashBaseText).push_back(((this->_hashBaseText).at(i-1) * this->_ALPHABET_SIZE + (this->_txt).at(i-1) - this->_initChar) % this->_mod);
  18. if (!rebuildHashPatBase) return;
  19. long patLen = (this->_pat).length();
  20. this->_hashBasePat = 0;
  21. for (long i = 1; i <= patLen; ++i) this->_hashBasePat = (this->_hashBasePat * this->_ALPHABET_SIZE + (this->_pat).at(i-1) - this->_initChar) % this->_mod;
  22. };
  23. public:
  24. HashPatternSearcher(const string pattern, const string text = string(), const char initCharacter = 'a', const long long modulo = ((long long)1<<(long long)31)-(long long)1) {
  25. this->_pat = pattern;
  26. this->_txt = text;
  27. this->_initChar = initCharacter;
  28. this->_mod = modulo;
  29. this->buildHashBase(true);
  30. };
  31. void resetText(const string text = string()) {
  32. this->_txt = text;
  33. this->buildHashBase();
  34. };
  35. void resetInitChar(const char initCharacter = 'a', const bool rebuildHashBase = true) {
  36. this->_initChar = 'a';
  37. if (rebuildHashBase) buildHashBase(true);
  38. };
  39. void resetModulo(const long long modulo = ((long long)1<<(long long)31)-(long long)1, const bool rebuildHashBase = true) {
  40. this->_mod = modulo;
  41. if (rebuildHashBase) buildHashBase(true);
  42. };
  43. long long getTextHash(long start, long end) {
  44. ++start, ++end;
  45. return ((this->_hashBaseText).at(end) - (this->_hashBaseText).at(start-1) * (this->_powVec).at(end-start+1) + this->_mod * this->_mod) % this->_mod;
  46. };
  47. long long getPatternHash() {
  48. return this->_hashBasePat;
  49. };
  50. vector<long> getOccurrences() {
  51. vector<long> res;
  52. long txtLen = (this->_txt).length();
  53. long patLen = (this->_pat).length();
  54. long limit = txtLen-patLen+1;
  55. for (long i = 0; i < limit; ++i) if (this->getTextHash(i, i+patLen-1) == this->_hashBasePat) res.push_back(i);
  56. return res;
  57. };
  58. long getOccurrences(vector<long>& vec) {
  59. return (vec = this->getOccurrences()).size();
  60. };
  61. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement