String
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 813 Accepted Submission(s): 258
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?
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) .
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
题目链接:点击打开链接
给出一个字符串和需要的字符串长度, 输出复合要求子串个数.
头尾指针移动, 等于需要字符串长度时计算尾指针距离末尾长度, 得到子串个数累加.
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "queue"
#include "stack"
#include "cmath"
#include "utility"
#include "map"
#include "set"
#include "vector"
#include "list"
#include "string"
#include "cstdlib"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define st first
#define nd second
#define exp 1e-8
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6 + 6;
int t, k, len, st, ed, cnt, num[30];
char s[MAXN];
std::map<char, int> mp;
int main(int argc, char const *argv[])
{
scanf("%d", &t);
while(t--) {
memset(num, 0, sizeof(num));
scanf("%s%d", s, &k);
len = strlen(s), st = 0, ed = 0, cnt = 0;
ll ans = 0;
while(st < len) {
if(st) {
num[s[st - 1] - 'a']--;
if(!num[s[st - 1] - 'a']) cnt--;
}
while(cnt < k && ed < len) {
if(!num[s[ed] - 'a']) cnt++;
num[s[ed] - 'a']++;
ed++;
}
if(cnt >= k) ans += len - ed + 1;
st++;
}
printf("%lld\n", ans);
}
return 0;
}