字符串Hash入门
字符串Hash可以通俗的理解为,把一个字符串转换为一个整数。
Hash方法
自然溢出方法
单Hash法
双Hash方法
获取子串的Hash
获取子串的Hash的栗子:
Oulipo
题意:
给你两个字符串,求第一个字符串在第二个字符串中出现的次数。
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e7+1;
#define base 131
//hash字符串大部分模板用的是ull,本题ll也能过
ull p[N];
ull ash[N];
ull a1;
ull gethash(int l, int r) //子字符串hash模板
{
return ash[r] - ash[l-1] * p[r-l+1];
}
int main()
{
ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
//加速cin,cout加上不容易超时
int T;
cin >> T;
p[0] = 1;
for (int i = 1; i <= 1000000; i++) //先处理p^i
p[i] = p[i-1] * base;
while (T--)
{
ash[0] = 0;
a1 = 0;
//string 可换成char[]
string a, b;
int lena, lenb;
cin >> a >> b;
lena = a.size();
lenb = b.size();
for (int i = 1; i <= lena; i++) //hash处理a
a1 = a1 * base + a[i - 1];
for (int i = 1; i <= lenb; i++)//hash处理 b
ash[i] = ash[i - 1] * base + b[i - 1];
int sum = 0;
for (int i = 1; i + lena - 1 <= lenb; i++)
{
if (a1 == gethash(i, i + lena - 1))
sum++;
}
cout << sum << endl;
}
}
Power Strings
题意:
求重复子字符串的数量。
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e6+1;
char a[N];
ull p[N];
ull hash[N];
int base = 31;
int main()
{
p[0]=1;
for(int i=1;i<N;i++)
p[i]=p[i-1]*base;
while(~scanf("%s",a))
{
if(a[0]=='.') break;
int len=strlen(a);
ll n=0;
hash[len]=0;
for(int i=len-1;i>=0;i--)
{
hash[i]=hash[i+1]*base+a[i]-'a'+1; //字符串Hash
}
for (int k = 1; k<=len; ++k)
{
if (len%k != 0) continue;
ll temp = hash[0]-hash[k]*p[k]; //temp子字符串
int j = 0;
for (j = k; j < len; j = j + k)
{
if (temp != hash[j] - hash[j + k] * p[k]) break;
//判断后面是否和temp相同
else temp = hash[j] - hash[j + k] * p[k];
}
if (j == len) //遍历到了最后
{
n=len/k; //求重复子串的数量
break;
}
}
cout << n <<endl;
}
}