概述
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("%lldn",res);
}
return 0;
}
最后
以上就是现实含羞草为你收集整理的HDU-5672-String(思维+尺取)的全部内容,希望文章能够帮你解决HDU-5672-String(思维+尺取)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复