topic
A string s of length n, which contains only the four characters 'Q', 'W', 'E', 'R'.
If the number of occurrences of the four characters in the character string is n / 4, it is a balanced character string.
Now you can replace a continuous substring in s with an arbitrary string of the same length that contains only those four characters, making it a balanced string. What is the minimum length of the replacement substring?
If s is balanced, then output 0 .
Input
A line of characters represents the given string s.
1 <= n <= 10 ^ 5.
n is a multiple of 4.
The string contains only the characters 'Q', 'W', 'E' and 'R'.
Output
An integer represents the answer.
Sample Input
QQWE
Sample Output
1
Ideas
Since the answer is a continuous interval and the left and right ends of the interval have a clear direction of movement, the ruler method can be used.
When the selected interval is within the range, that isR<n&&L<=RTime, loop.
Assuming that the interval [L, R] is selected:
- Use sum1, sum2, sum3, sum4 to record separatelyNot includedIn the interval [L, R], the number of characters 'A', 'B', 'C', 'D';
- MAX = max(sum1, sum2, sum3, sum4);
- TOTAL=R–L+1;
- FREE = TOTAL - [(MAX-sum1)+(MAX-sum2)+(MAX-sum3)+(MAX-sum4)]。
If FREE> = 0 and a multiple of 4, the requirements are met; otherwise, they are not satisfied.
Iffulfil requirements,thenL++, At the same time, compare the interval length obtained at this time with the minimum value of the interval length obtained before, and update ans = min (ans, R-L + 1);Otherwise R ++。
Code
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
char c[100005];
map<char,int> sum;
int main() {
int n=0;
sum['Q']=0;sum['W']=0;sum['E']=0;sum['R']=0;
while(scanf("%c",&c[n])!=EOF){
sum[c[n]]++;
n++;
}
if(sum['Q']==sum['W']&&sum['W']==sum['E']&&sum['E']==sum['R']){
printf("0");
return 0;
}
int l=0,r=0,ans=n;
sum[c[0]]--;
while(r<n&&l<=r){
int Max=max(max(sum['Q'],sum['W']),max(sum['E'],sum['R']));
int total=r-l+1;
int free=total-(Max-sum['Q'])-(Max-sum['W'])-(Max-sum['E'])-(Max-sum['R']);
if(free>=0&&free%4==0){//符合要求,左边界右移1
ans=min(ans,total);
sum[c[l]]++;
l++;
}
else{//不符合要求,右边界右移1
r++;
if(r<n)
sum[c[r]]--;
}
}
printf("%d",ans);
return 0;
}
to sum up
The first time I used map, I felt very happy.
Title link