String Algorithms
String Hashing
String hashing is a method to compare the equality of two strings in O(1) rather than the naive O(n) solution.
The hash is given by
hash(s)=∑i=0n−1s[i]⋅pimodm
where p and m are some chosen positive numbers:
- If the input string s is only lowercase, use p=31
- Else, if both uppercase and lowercase, use p=53
- Use m=109+9
Polynomial Hashing
We can implement String Hashing with Polynomial Hashing.
Hash of substrings
The greater power is when we want to compare substrings of a string. The following code counts the number of unique substrings.
USACO Implementation
A template from here https://usaco.guide/gold/hashing?lang=cpp