题目传送门
题意
给定 个字符串,对于每个字符串 ,输出使其变为“五字神人”的最小操作次数。其中“五字神人”的定义为对于字符串 ,要求 或 中的大写字母的个数为5。
思路
根据题意,我们可以尝试分类讨论。先根据 的值来分类,当 时,在 的末尾加上 个字母,即为操作次数;当 时,说明已满足条件,输出 ;当 时,我们分别对删去任意字符使其长度满足要求、将小写字母改为大写字母使大写字母个数满足要求(大写字母个数应小于 )、将大写字母改为小写字母使大写字母个数满足要求(大写字母个数应大于 ,这个答案和删去字母使得大写字母个数满足要求的答案是一样的,所以可以少讨论一种)。再在这些答案中取最小值即为题目所求。
代码
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int t,ans;
string s;
int main (){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
while (t--){
ans=0x3f3f3f3f;
cin >> s;
int len=s.size(),upper=0;
for (int i=0;i<len;i++){
if (isupper(s[i])){
upper++;
}
}
if (len==5||upper==5){
cout << 0 << endl;
continue;
}
//len<5
if (len<5){
ans=5-len;
}else {
//删字符,直到长度=5
ans=min(ans,len-5);
if (upper<5){
ans=min(ans,5-upper); //改小写字母至大写,直到大写=5(upper<5)
}else {
ans=min(ans,upper-5); //改大写至小写,直到大写=5(upper>5)
}
}
cout << ans << endl;
}
return 0;
}