[双指针] aw3768. 字符串删减(模拟+STL)

1. 题目来源

链接:3768. 字符串删减

2. 题目解析

模拟。

线性扫描即可,cnt 记录连续 x 的数量,如果 cnt==3 说明连续 3 个需要删除末尾这个 x,在此仅需 cnt-- 即可。遇见非 x 字母,直接将 cnt=0 即可。

双指针也可,找到连续一段 xxx,删成 2 个即可。


时间复杂度: O ( n ) O(n) O(n)

空间复杂度: O ( n ) O(n) O(n)


模拟+计数

#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    string s;
    cin >> n >> s;
    int res = 0, cnt = 0;
    for (char &c : s) {
        if (c == 'x') {
            cnt ++ ;
            if (cnt == 3) {
                res ++ ;
                cnt -- ;
            }
        } else cnt = 0;
    }
    cout << res << endl;
    
    return 0;
}

双指针

#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    string s;
    cin >> n >> s;
    int res = 0, cnt = 0;
    for (int i = 0; i < n; i ++ ) {
        if (s[i] != 'x') continue;
        int j = i + 1;
        while (j < s.size() && s[j] == 'x') j ++ ;
        res += max(0, j - i - 2);
        i = j - 1;
    }
    
    cout << res << endl;
    
    return 0;
}

STL

#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    string s;
    cin >> n >> s;
    int res = 0;
    while (s.find("xxx") != -1) {
        s.erase(s.begin() + s.find("xxx") + 2);
        res ++ ;
    }
    
    cout << res << endl;
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值