Problem Description
You are given a string S consisting of lowercase letters, and your task is counting the number of substring that the number of each lowercase letter in the substring is no more than K.
Input
In the first line there is an integer T , indicates the number of test cases.
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
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
Output
For each case, output a line contains the answer.
Sample Input
3 abc 1 abcabc 1 abcabc 2
Sample Output
6 15 21
题意:输入一个字符串,找出重复字母个数不超过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);
}

本文介绍了一种利用双指针法解决特定字符串问题的方法,即在一个字符串中找出所有子串,使得这些子串中每个字母的出现次数不超过给定值K。文章通过示例解释了算法的基本思想,并提供了完整的C++代码实现。
1417

被折叠的 条评论
为什么被折叠?



