For each case, the first line contains a string which only consist of lowercase letters. The second line contains an integer K.
[Technical Specification]
1<=T<= 100
1 <= the length of S <= 100000
1 <= K <= 100000
Sample Output
题意:输入一个字符串,找出重复字母个数不超过K个的字串的个数。
思路:使用的是双指针法也叫窗口移动或尺取法。定义两个指针,始终保持指针内的子串符合题目要求,向右移动右指针,若不符合要求,则将左指针向右移动直到指针内的子串符合题目要求为止。这样就求出了每个点向左延伸最远符合要求的点。一个长度为n的字符串它的字串个数为1+2+..+n。
#include <stdio.h>
#include <string.h>
char s[100010];
int flag[100010];
int main()
{
int t,k,i;
__int64 sum;
scanf("%d%*c",&t);
while(t--)
{
memset(flag,0,sizeof(flag));
sum=0;
scanf("%s",s);
scanf("%d",&k);
int len=strlen(s),pos=0;
for(i=0;i<len;i++)
{
flag[s[i]-'a']++;
if(flag[s[i]-'a']>k)
{
while(s[pos]!=s[i])
{
flag[s[pos]-'a']--;
pos++;
}
flag[s[pos]-'a']--;
pos++;
}
sum += i+1-pos;
}
printf("%I64d\n",sum);
}