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);
}