Boring count 尺取 暴搜

先复制一波题面:
You are given a string S consisting of lowercase letters, and your task is counting the number of substring that the number of each lowercase letter in the substring is no more than K.

Input In the first line there is an integer T , indicates the number of test cases.
For each case, the first line contains a string which only consist of lowercase letters. The second line contains an integer K.

[Technical Specification]
1<=T<= 100
1 <= the length of S <= 100000
1 <= K <= 100000 Output For each case, output a line contains the answer. Sample Input
3
abc
1
abcabc
1
abcabc
2
Sample Output
6
15
21
题目中说计算子字符串长度,但从样例中我们看到abc,k=1时答案是6。呢么实际上是取了a b c ab bc abc这6个情况,即实际为子区间而不是子串。因此题目转化成了有序序列求取最长区间的问题了,这里我就可以使用双指针的思想来做这道题。设两个位置初始位置和末位置,然后按照顺序寻找小于等于k的最长子区间。呢么在找到第二个子区间的时候可能会与之前的重合呢么实际上第二个区间子串的数量等于总数减去重复部分。例abcabc第一个子区间是abc 有 1+ 2 +3 = 6个第二个子区间bca 和第一个区间中重复了bc 即长度为3 + 2 + 1 - (2 + 1)。附代码:
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int main()
{
    long long  t;
    cin >> t;
    while(t--){
        char s[100001];
        long long  le[27] = {},k;
        long long  n = 0;
        cin >> s >> k;
        n = strlen(s);
        long long  st = 0,en = -1,ds1 = 0,ds2 = 0,res = 0,rc = 0;
        while(1){
            while(en < n){
                if(++le[s[++en] - 'a'] > k ){
                    break;
                }
            }
            ds1 = en - st;
            res += ((ds1 + 1) * ds1) / 2 - ((ds2 + 1) * ds2) / 2;
            if(en == n)
                break;
            while(st < n){
				le[s[st++] - 'a']--;
                if(le[s[en] - 'a'] <= k){
                    if(st <= en)
                    ds2 = en - st;
                    break;
                }
            }
        }
            cout << res << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/happy_fakelove/article/details/79050481