string

string
There is a string S.S only contain lower case English character.(10≤length(S)≤1,000,000)
How many substrings there are that contain at least k(1≤k≤26) distinct characters?
Input
There are multiple test cases. The first line of input contains an integer T(1≤T≤10) indicating the number of test cases. For each test case:

The first line contains string S.
The second line contains a integer k(1≤k≤26).
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 <algorithm>

using namespace std;

typedef long long LL ;
LL num = 0 ;
const int N = 1e6+100 ;
int a[N] , b[35] ;
char s[N] ;
int k ;

int main()
{
    int t ;
    scanf("%d" , &t) ;
    while(t--)
    {
        scanf("%s" , s+1) ;
        scanf("%d" , &k) ;

        int len = strlen(s+1) ;

        memset(b , 0 , sizeof(b));

        for(int i = 1; i <= len ;i ++)
            a[i] = s[i] - 'a' + 1 ;

        int sum = 0 ;
        int l = 0 ;
        num = 0 ;

        for(int i = 1 ;i <= len ; i ++)
        {
            while(l + 1 <= len && sum < k)
            {
                l ++ ;
                b[a[l]]++ ;//记录每个字符
                if(b[a[l]] == 1)
                    sum ++ ;
            }
            if(sum == k)
                num += len-l+1 ;
            b[a[i]]-- ; //左指针右移
            if(b[a[i]]==0)
                sum-- ;
        }
        printf("%lld\n" ,num) ;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值