题目大意就是将一个字符串分成长度为N的字串。且每个子串中不同的字符不会超过NC个。问总共有多少个不同的子串。解题的方法把字符串中出现的 字符都用一个整数编号,然后把所有长度为N的子串对应的数字串转化为以NC作为进制的一个数字,再用哈希判断。由于题目说长度不会超过16,000,000 所以哈希长度就设为16000000就行。另外为每一个字符对应一个整数,来方便转化。
如题目中的
daababac与整数对应之后就是
12232324
然后子串
daa->122->011(因为是化为4进制,所以需要减1)->5(因为是4进制);
aab->223->112->22;
aba->232->121->25;
... ...
时间复杂度为O(string.length());
</pre><pre name="code" class="html">
</pre><pre name="code" class="html">#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <cmath>
using namespace std;
#define maxn 16000000
char s[maxn];
int ch[maxn];
int hash[maxn];
int main()
{
int i,j,k,t,m,n,nc;
scanf("%d%d",&n,&nc);
cin>>s;
int length = strlen(s);
int cnt = 0;
for(i=0;i<length;i++){
if(!ch[s[i]])
ch[s[i]] = cnt++;
if(cnt==nc)
break;
}
int ans = 0;
for(i=0;i<length-n+1;i++){
int sum = 0;
for(j=i;j<i+n;j++)
sum += sum*nc + ch[s[j]];
if(!hash[sum]){
ans++;
hash[sum]=1;
}
}
printf("%d\n",ans);
return 0;
}