我试图解决一个问题,我必须在字符串中找到长度为“plen”的回文数量。(最多长度为30000)。我想过使用滚动哈希技术来计算长度为plen的所有子串的哈希值及其反向值。如果哈希匹配,我假设相等,希望我选择的常量应该足够。以下是我的实现,我好像搞砸了。它也不适用于简单的情况。有人能告诉我我的错误吗?感谢。
int MUL = 37;
int MOD = 9999991;
for(int i = 1 , pwr = 1 ; i < plen ; i++) pwr = (pwr * MUL) % MOD;
long long hash = number[0];
long long revHash = number[plen - 1];
for(int i = 1 ; i < plen ; i++)
{
hash = (MUL*hash + number[i])%MOD;
revHash = (revHash*MUL + number[plen - i - 1])%MOD;
}
cout << hash << " " << revHash <<"\n";
int cnt = (hash == revHash);
for(int i = plen ; i < numbers ; i++)
{
hash = (hash + (MOD - pwr)*number[i - plen])%MOD;
hash = (hash*MUL + number[i])%MOD;
revHash = ((revHash + MOD - number[i - plen]))%MOD;
revHash = (revHash + pwr*number[i])%MOD;
cnt += (hash == revHash);
cout << hash << " " << revHash << "\n";
}