这题是道字符串匹配问题。。比较容易,赛间TLE了多次。。我真是傻。
用两次stack模拟就可以做了。
下面附上代码。
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=2e5+10;
char a[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",&a);
int len=strlen(a);
int ans=0,x=0,y=0;
for(int i=0;i<len;i++)
{
if((a[i]=='a'||a[i]=='A')) x++;
if((a[i]=='c'||a[i]=='C')&&x)
{
x--;
y++;
}
if((a[i]=='m'||a[i]=='M')&&y)
{
y--;
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}
赛后了解到了另一种比较易懂的做法,用到了一个以前不知道的函数,toupper()可以将小写字母转换为大写。记下,方便以后学习。
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=2e5+10;
char a[maxn];
int b[3];
char c[3]={'A','C','M'};
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",&a);
int len=strlen(a);
memset(b,0,sizeof(b));
for(int i=0;i<len;i++)
{
a[i]=toupper(a[i]);//小写字母转换成大写字母
for(int j=0;j<3;j++)
{
if(a[i]==c[j])
{
if(j==0)b[j]++;
if(j&&b[j]<b[j-1])b[j]++;
}
}
}
printf("%d\n",b[2]);
}
return 0;
}