hdu 5672 String

本文介绍一种高效算法,用于计算字符串中至少包含k种不同字符的所有子串数量。采用尺取法,通过两个下标移动,实现快速遍历与计数,适用于处理大规模字符串数据。

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2370    Accepted Submission(s): 780


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
 

 

Source
 

 

Recommend
wange2014   |   We have carefully selected several similar problems for you:   6447  6446  6445  6444  6443 
 
求包含不同字母数不小于k的子串数。尺取法,两个下标移动,当tail移动到head~tail包含了k个不同的字母时,ans就加len - tail + 1,加上后面的字母组成的子串满足条件,然后移动head,每次移动ans都加len - tail + 1,直到head~tail包含不同的字母不足k时再次移动tail。
 
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#define inf 0x3f3f3f3f
#define MAX 302
using namespace std;
int main() {
    int t,k,v[30];
    char s[1000005];
    scanf("%d",&t);
    while(t --) {
        scanf("%s%d",s,&k);
        long long ans = 0;
        int len = strlen(s);
        int c = 0;
        memset(v,0,sizeof(v));
        int head = 0,tail = 0;
        while(tail < len) {
            int d = s[tail ++] - 'a';
            if(!v[d]) c ++;
            v[d] ++;
            if(c >= k) {
                while(head <= tail) {
                    int e = s[head ++] - 'a';
                    v[e] --;
                    ans += len - tail + 1;
                    if(!v[e]) {
                        c --;
                        break;
                    }
                }
            }
        }
        printf("%lld\n",ans);
    }
}

 

转载于:https://www.cnblogs.com/8023spz/p/9745851.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值