题解:P12341 [蓝桥杯 2025 省 A/Python B 第二场] 消消乐

· · 题解

题意:

在给定的字符串 s 中,尽可能多地消去 A 和 B 的组合(A 在前,B 在后),直到无法继续操作。最终返回剩余字符的数量。

思路:

为了最大化消去的对数,我们应尽可能让前面的 A 和后面的 B 匹配,考虑使用双指针。

Code:

#include<bits/stdc++.h>
using namespace std;
string s;
int main() 
{
    cin >> s;
    int l=0,r=s.size()-1,c=0;
    while(l<r)
    {
        while(l<r&&s[l]!='A') l++;
        while(l<r&&s[r]!='B') r--;
        if (l<r) c++,l++,r--;
    }
    cout << s.size()-2*c;
}