一,题目:
给你一个字符串S,S只包含大写英文字母,以及给你3个正整数k1,k2,k3
现在你需要计算有多少个非空连续的子串同时满足:
- 子串中字母A的个数不超过k1
- 子串中字母C的个数不超过k2
- 子串中字母M的个数不超过k3
输入格式:
输入有2行
第1行4个正整数,n(1≤n≤106)表示字符串的长度,k1,k2,k3(1≤k1,k2,k3≤106)
第2行一个字符串S,保证只包含大写英文字母
输出格式:
输出只有一行一个整数,表示你计算的答案
输入样例:
5 1 2 1
ACMMB
输出样例:
9
样例解释:
满足条件的非空连续子串有:A,C,M,M,B,AC,ACM,CM,MB,一共9个
二,思路:
这是一道很经典的双指针题目,和求最长不重复连续字串相似,但是好多细节。
三,代码:
#include <iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<set>
#include<stack>
#include<queue>
#include<map>
using namespace std;
#define x first
#define y second
const int N=2e5+10,M=1e9+7;
typedef long long ll;
typedef pair<int,int> pii;
void Solved() {
int n,k1,k2,k3,k;
cin>>n>>k1>>k2>>k3;
string str;
cin>>str;
map<char,int> m;
ll sum=0;
int i,j;
for( i=0,j=0;i<n;i++){
if(str[i]=='A'||str[i]=='M'||str[i]=='C'){
m[str[i]]++;
if(str[i]=='A') k=k1;
if(str[i]=='C') k=k2;
if(str[i]=='M') k=k3;
//当m[str[i]]>k说明一定是字母str[i]数量超了
//那么移动j指针,计算累加数量,直到m[str[i]]<=k
while(j<i&&m[str[i]]>k){
sum+=i-j;
if(str[j]=='A'||str[j]=='C'||str[j]=='M'){
m[str[j]]--;
}
j++;
}
}
}
while(j<i){
sum+=i-j;
j++;
}
cout<<sum<<endl;
}
int main()
{
int t;
t=1;
while(t--) {
Solved();
}
return 0;
}