hdu 5672 Strings 模拟

子串字符计数算法
本文介绍了一种高效的算法,用于解决给定字符串中至少包含k个不同字符的所有子串的数量计算问题。通过一次遍历并使用特定计数技巧,避免了超时问题。

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 integerT(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 leastk dictinct characters.
 

Sample Input
2 abcabcabca 4 abcabcabcabc 3
 

Sample Output
0 55
 
题目:给一个字符串,问有多少个子串至少含有k个不同的字母?

分析:从头开始扫一遍,如果遇见第一次出现过的,就计数cnt++,直到cnt==k,那么就从那个子串的开头开始删去字符,根据删除的字符出现的次数,做出相应的判断。

如果用map判断是否出现过会超时。

#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<stack>
using namespace std;
typedef long long ll;
const int N=1e6+9;
char s[N];
int k;
int vis[300];
int main()
{
    //freopen("f.txt","r",stdin);
    int T;scanf("%d",&T);
    while(T--){
        scanf("%s%d",s,&k);
        int slen=strlen(s);
        if(k==1){
            printf("%I64d\n",(ll)slen*(slen+1)/2);continue;
        }
        int head=0;
        ll ans=0;
        int cnt=0;
        memset(vis,0,sizeof(vis));
        for(int i=0;i<slen;i++){
            if(vis[s[i]]>0){
                vis[s[i]]++;
                continue;
            }
            vis[s[i]]=1;
            cnt++;
            if(cnt==k){
                while(head<i){
                    ans+=slen-i; 
                    if(vis[s[head]]==1){
                        vis[s[head]]=0;
                        head++;
                        cnt--;
                        break;
                    }
                    else{
                        vis[s[head]]--;head++;
                    }
                }
            }
        }
        printf("%I64d\n",ans);
    }
    return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值