Solving problems
Find the position or number of T occurrences in S. Suppose the length of S is N, T is M, and the hash value of the string that enumerates s length m is compared to the hash value of T. The optimization using a scrolling hash at this point does not have the complexity of O (MN).
Algorithm description Scrolling Hash
Take two appropriate primes B and H, assuming the string c = c1c2c3c4, define the hash function:
H (C) = (c1bm-1 + c2bm-2 + c3bm-3 + ... + cmb0) mod h
where B is the cardinality, which is equivalent to the string as a B-binary. When calculating the M-long string in S, the hash value of the string after each backward slide of one character and the Hahs value of the previous string have the following relationship:
H (s[k+1. k+m]) = h (s[k). K+M-1] * B-SKBM + sk+m) mod h
This computes the hash value to calculate the hash value of all positions in s in the time of O (n), thus completing the string match in the time of O (M + N).
Hit: The actual use of the H is 264, using a long long int natural overflow eliminates the time to take the modulus.
PS: The original r-k algorithm also needs to check for hash value collisions, but this will degrade the algorithm complexity to O (MN), and the race is only relatively non-checked.
Template
1 Long Long int ull;
Rabin-karp ACM Training