#include <bits/stdc++.h>
#define m 1000000007
#define N (int)2e6 + 3
usingnamespace std;
longlong pows[N], h[N], h2[N];
set<int> ss;
int main()
{
string s = "www.cplusplus.com/forum";
// powers array
pows[0] = 1;
int n = s.length(), p = 31;
for(int i = 1; i < n; i++){
pows[i] = pows[i-1]*p;
pows[i] %= m;
}
// hash from 0 to i array
h[0] = s[0]-'a'+1;
for(int i = 1; i < n; i++){
h[i] = h[i-1] + (s[i]-'a'+1)*pows[i];
h[i] %= m;
}
// storing each hash with 9 characters in a set
ss.insert(h[8]);
for(int i = 9; i < n; i++){
int tp = h[i] - h[i-9]*pows[i-8];
tp %= m;
tp += m;
tp %= m;
ss.insert(tp);
}
// print hashes with 9 characters
set<int>::iterator itr = ss.begin();
while(itr != ss.end()){
cout << *(itr++) << " ";
}
cout << endl;
// t is the string that i want to check if it is exist in s
string t = "cplusplus";
int n2 = t.length();
h2[0] = t[0]-'a'+1;
for(int i = 1; i < n2; i++){
h2[i] = h2[i-1] + (t[i]-'a'+1)*pows[i];
h2[i] %= m;
}
// print t hash
cout << h2[n2-1] << endl;
return 0;
}
That code gives me a wrong result.
The hash of t should be one of the stored hashes in the set but it doesn't.
Is the wrong in way or in code or in powers or what ?
thanks in advance.
dhayden
the hash of t should be one of the stored hash because it's a substring of s
that's if the hashing way which i'm using is correct, but it isn't.
I discovered the wrong, but if you have any comment in my code till me.