[周賽] 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);
    }



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