Advertisement
dipBRUR

17

Nov 19th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. Algorithm : Z Algorithm
  2.  
  3. void matchPattern(string text, string pattern) {
  4. string concate = pattern + "$" + text;
  5. int lenText = text.length(), lenPat = pattern.length();
  6. VI Z = getZarr(concate);
  7. for (int i=0; i<concate.length(); i++) {
  8. if (Z[i] == lenPat)
  9. cout << "Pattern Found at " << (i-lenPat-1) << endl;
  10. }
  11. }
  12.  
  13. Algorithm : Robin Carp string matching, Double Hash
  14. Compleixity : O(n + m)
  15.  
  16. const ll B = 347;
  17. const ll M = 1e9+7;
  18.  
  19. const ll Btemp = 313;
  20. const ll Mtemp = 1e9+9;
  21.  
  22. PLL Hash(const string &s, int m) { // double hash
  23. ll power = 1;
  24. ll powertemp = 1;
  25.  
  26. ll h = 0;
  27. ll htemp = 0;
  28.  
  29. for (int i=m-1; i>=0; i--) {
  30. h = h + (s[i]*power) % M;
  31. h = h % M;
  32.  
  33. power = (power*B) % M;
  34. htemp = htemp + (s[i]*powertemp) % Mtemp;
  35. htemp = htemp % M;
  36. powertemp = (powertemp*Btemp) % Mtemp;
  37. }
  38. return mk(h, htemp);
  39. }
  40.  
  41. ll match(const string &text, const string &pattern) {
  42. int n = text.size();
  43. int m = pattern.size();
  44. if (n < m)
  45. return -1;
  46. if (n==0 or m==0)
  47. return -1;
  48. PLL hash_t = Hash(text, m);
  49. PLL hash_p = Hash(pattern, m);
  50.  
  51. ll hash_text = hash_t.first;
  52. ll hash_text_temp = hash_t.second;
  53.  
  54. ll hash_pattern = hash_p.first;
  55. ll hash_pattern_temp = hash_p.second;
  56.  
  57. if (hash_text==hash_pattern and hash_text_temp==hash_pattern_temp)
  58. return 0;
  59. ll power = 1;
  60. ll powertemp = 1;
  61. for (int i=1; i<=m-1; i++) {
  62. power = (power*B) % M;
  63. powertemp = (powertemp*Btemp) % Mtemp;
  64. }
  65. for (int i=m; i<n; i++) {
  66. hash_text = (hash_text - (text[i-m]*power) % M) % M;
  67. hash_text = (hash_text + M) % M;
  68. hash_text = (hash_text * B) % M;
  69. hash_text = (hash_text + text[i]) % M;
  70.  
  71. hash_text_temp = (hash_text_temp - (text[i-m]*powertemp) % Mtemp) % Mtemp;
  72. hash_text_temp = (hash_text_temp + Mtemp) % Mtemp;
  73. hash_text_temp = (hash_text_temp * Btemp) % Mtemp;
  74. hash_text_temp = (hash_text_temp + text[i]) % Mtemp;
  75.  
  76. if (hash_text == hash_pattern and hash_text_temp == hash_pattern_temp) {
  77. return i-m+1;
  78. }
  79. }
  80. return -1;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement