Boring count HDU - 5056 (尺取)

Boring count

题目链接:HDU - 5056 

题意:一个仅由小写字母构成的字符串,找出串中每个字母的个数不大于k的子串的个数;

思路:不断增缩区间,维护每个字母的个数<=k,这样每次截取的子串中有选择以区间首字母为首的子串就满足条件共有区间长度个子串;

#include <bits/stdc++.h>
using namespace std;
char s[100010];
int cnt[30];
bool check(int x, int k){
	if(cnt[s[x]-'a']+1<=k) return true;
	return false;
}
int main(){
	int T;
	scanf("%d", &T);
	while(T--){
		memset(cnt, 0, sizeof(cnt));
		scanf("%s", s);
		int k;
		scanf("%d", &k);
		int len=strlen(s);
		cnt[s[0]-'a']=1;
		long long ans=0;
		for(int i=0, j=0; i<len; i++){
			while(check(j+1, k)&&j+1<len){
				cnt[s[j+1]-'a']++;
				j++;
			}
			//cout << i << ' ' << j << endl;
			ans+=(j-i+1);
			cnt[s[i]-'a']--;
		}
		printf("%lld\n", ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sirius_han/article/details/81121195