CF1660C Get an Even String 题解
本蒟蒻第三篇题解。
这是一道好题,有那么一丢丢的思维。
下面讲一下思路:
-
读入部分省略。
-
答案为
ans ,ans 初值为s 字符串的长度,因为后面要不断地减。 -
还有一个桶
f , 用来记录每个字母出现的个数。 -
从前到后将
s 串扫描一遍,每次统计每个字母出现的个数,然后判断这个字母是不是已经出现了两次,如果是的,则将ans-=2, 然后将桶清空。 -
这里解释一下为什么要将桶清空:因为这个字母已经出现了两次,说明这个字母已经可以匹配了,所以现在统计的其他字母都没用了,所以将桶清空。
-
最后输出
ans 即可。
下面附上 AC 代码:
#include <cstdio>
#include <cstring> //strlen、memset函数所在的库
#define maxn 200005
#define maxm 35
using namespace std;
int t,ans;
int f[maxm];
char s[maxn];
inline void in(int &a){ //快速读入
a=0;char ch=getchar();
while(ch<'0'||ch>'9')
ch=getchar();
while(ch>='0'&&ch<='9'){
a=(a<<1)+(a<<3)+(ch^48);
ch=getchar();
}
}
int main(){
in(t);
while(t--){
memset(f,0,sizeof(f));
scanf("%s",s);
ans=strlen(s); //将ans赋值为s串的长度
//strlen函数的作用是测量字符串的长度
for(int i=0;s[i];++i){ //见思路
f[s[i]-'a']++;
if(f[s[i]-'a']==2){
ans-=2;
memset(f,0,sizeof(f));
}
}
printf("%d\n",ans);
}
return 0;
}