Skip to content

Instantly share code, notes, and snippets.

@agasiev
Created December 2, 2012 19:06
Show Gist options
  • Save agasiev/4190479 to your computer and use it in GitHub Desktop.
Save agasiev/4190479 to your computer and use it in GitHub Desktop.
Rabin-Karp algorithm
int main()
{
std::string str;
std::string substr;
cin >> str;
cin >> substr;
if (str.length() < substr.length()) {
return 0;
}
int p_base = 53;
std::vector<long long> powers(str.length());
powers[0] = 1;
for (size_t i = 1; i < powers.size(); i++)
powers[i] = powers[i - 1] * p_base;
std::vector<long long> str_hashes(powers.size());
for (int i = 0; i < str_hashes.size(); i++) {
str_hashes[i] = (str[i] - 'a' + 1) * powers[i];
if (i) str_hashes[i] += str_hashes[i - 1];
}
long long substr_hash = 0;
for (size_t i = 0; i < substr.size(); i++) {
substr_hash += (substr[i] - 'a' + 1) * powers[i];
}
for (size_t i = 0; i + substr.length() - 1 < str.length(); ++i) {
long long hash_t = str_hashes[i + substr.length() - 1];
if (i) hash_t -= str_hashes[i-1];
if (hash_t == substr_hash * powers[i]) {
std::cout << i << " ";
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment