HDU-5672-String(思维+尺取)

String

Problem Description

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

解题思路:

尺取,利用左右指针的移动标记区间内不同数的个数。
左指针移动一次就判断一次能不能加到最后的答案。
如果目前l-r区间的个数不小于k个 那么所有右边界大于r的区间都满足条件。相当于枚举左边界,计算右边界。右边界的个数就等于len-r。
第一次交用map+cin超时了,改成scanf+mark[]就只用了124ms

AC代码:

#include <bits/stdc++.h>
#define int long long
using namespace std;

const int N = 1e6+10;
int mark[30];
char s[1000002];
signed main()
{
    int t;
    scanf("%lld",&t);
    while(t--)
    {
        int cnt = 0,k,res = 0;
        memset(mark,0,sizeof(mark));
        scanf("%s%lld",s,&k);
        int len = strlen(s);
        int l = 0,r = 0;
        while( r != len)
        {
            if(mark[s[r] - 'a'] == 0)
                cnt++;
            mark[s[r] - 'a'] ++;
            while(l <= r && cnt >= k)
            {
                res += len-r;
                mark[s[l] - 'a'] --;
                if(mark[s[l] - 'a'] == 0)
                    cnt --;
                l ++;
            }
            r ++;
        }
        printf("%lld\n",res);
    }
    return 0;
}

发布了104 篇原创文章 · 获赞 7 · 访问量 4088

猜你喜欢

转载自blog.csdn.net/qq_43461168/article/details/103294305