题解:P12341 [蓝桥杯 2025 省 A/Python B 第二场] 消消乐
解题思路
这道题要我们消除到不能再消除时,字符串长度最大。
很明显,我们一定要用尽量前的
剩下来的模拟即可,这样写是最优解。
代码
#include<bits/stdc++.h>
using namespace std;
string x;
long long ans;
long long l,r;
int main(){
cin>>x;
ans=x.size();//字符串长度
l=0,r=x.size()-1;
while(l<r){
while(l<x.size() && x[l]!='A'){
l++;//找尽量前的A
}
while(r>=0 && x[r]!='B'){
r--;//找尽量后的B
}
if(l>=r){
break;
}
ans-=2;//消除一对
l++;
r--;
}
cout<<ans;
return 0;
}