Skip to content

Instantly share code, notes, and snippets.

@AfvanMoopen
Created August 22, 2022 12:05
Show Gist options
  • Save AfvanMoopen/7c0ec647858ed7fab3b08423af08537a to your computer and use it in GitHub Desktop.
Save AfvanMoopen/7c0ec647858ed7fab3b08423af08537a to your computer and use it in GitHub Desktop.
long long compute_hash(string s) {
const int p = 31; //prime number
const int m = 1e9 + 9;
long long hash_value = 0;
long long p_pow = 1;
for(char c : s) {
hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
p_pow = (p_pow * p) % m;
}
return hash_value;
}
long long rolling_hash(string prev , char nxt)
{
const int p = 31;
const int m = 1e9 + 9;
long long H = compute_hash(prev)
long long Hnxt = ((H - pow(prev[0] , prev.length() - 1)) * p + (int)nxt) % m;
return Hnxt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment