[周赛] HDU-5056 Boring count

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
 

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章