HNU 程序设计训练 3.19 ab串

考虑前缀和,将a记为1,b记为0

则对于区间[i,j),a的个数即为pre[j-1]-pre[i-1],b的个数为i-j-(pre[j-1]-pre[i-1])

遍历i,j更新最大值即可,复杂度O(N^2)

【问题描述】

       给定一个由字符'a'和字符'b'组成的字符串,可以删除若干字符,使得剩下来的字符串满足前后段为a,中间段为b(aaa....aaabbbb.....bbbbaaa.....aaa),区段可以没有字符(ba,ab,b,aa都是合法的),求最长剩下字符串的长度。

【输入形式】

      输入为一行一个长度不超过5000的非空字符串,字符串仅由符'a'和字符'b'组成。

【输出形式】

      输出为一个整数,表示符合要求的最长剩下字符串长度

【样例输入1】

abba

【样例输出1】

4

【样例输入2】

bab

【样例输出2】

2
// clang-format off
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define add emplace_back
#define arr(...) vector<__VA_ARGS__>
#define arrin(a) for (auto& i : a) cin >> i
#define multi_test int i; cin >> i; while (i--)
// clang-format on
const int inf = INT_MAX / 2;
const int mod = 998244353;
const int mxn = 2e5 + 10;
int test_case = 1;

void solve()
{
    // cerr << "\ntest " << test_case++ << ":\n";
    string s;
    cin >> s;
    int n = s.length();
    arr(int) pre(n + 1, 0);
    for (int i = 0; i < n; i++) {
        if (s[i] == 'a') {
            pre[i + 1] = pre[i] + 1;
        } else {
            pre[i + 1] = pre[i];
        }
    }
    int ans = 0;
    for (int i = 1; i <= n + 1; i++) {
        for (int j = i; j <= n + 1; j++) {
            ans = max(ans, pre[i - 1] + j - i - (pre[j - 1] - pre[i - 1]) + pre[n] - pre[j - 1]);
        }
    }
    cout << ans << '\n';
}

// clang-format off
int main()
{
    cin.tie(nullptr)->sync_with_stdio(false);
    // multi_test
    solve();
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值