String HDU5672

Problem Description
There is a string  S . S  only contain lower case English character. (10length(S)1,000,000)
How many substrings there are that contain at least  k(1k26)  distinct characters?
 

Input
There are multiple test cases. The first line of input contains an integer  T(1T10)  indicating the number of test cases. For each test case:

The first line contains string  S .
The second line contains a integer  k(1k26) .
 

Output
For each test case, output the number of substrings that contain at least  k  dictinct characters.
 

Sample Input
  
  
2 abcabcabca 4 abcabcabcabc 3
 

Sample Output
  
  
0 55

大意:

在一个字符串中任意取子串,求其至少有K个不同字母的子串个数。

#include<iostream>
#include<cstring>
#include<stdio.h>

using namespace std;

char str[1001000];
int num[26],k;

int main()
{
    //freopen("in.txt","r",stdin);
    int T;
    cin>>T;
    while(T--)
    {
        long long ans=0;
        memset(num,0,sizeof(num));
        cin>>(str+1)>>k;
        int cur=0,r=0,l=1,len=strlen(str+1);
        while(l<=len)
        {
        while(r<len&&cur<k)
        {
            r++;
            if(num[str[r]-'a']==0)
                cur++;
            num[str[r]-'a']++;
        }
        if(cur==k)
        {
             ans+=len-r+1;
             num[str[l]-'a']--;
             if(num[str[l++]-'a']==0)
                cur--;
             while(num[str[l-1]-'a'])
             {
                 ans+=len-r+1;
                 num[str[l]-'a']--;
                if(num[str[l++]-'a']==0)
                  cur--;
             }
        }
        else
            break;
        }

        cout<<ans<<endl;
    }


}

大体思路就是两个指针(数组下标)从左到右指,每次都使指中的区域不同字母数为K,加上所有情况。

切记,代码越简明越好。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值