蓝桥杯C组-填充-贪心

点击此处查看原题​​​​​​​

*思路:首先要求 00 11 尽可能的多,所以尽可能多的多配对,配对只在i , i + 1之间发生,所以只需要关注str[i] 和 str[i + 1]即可,如果str[i] == str[i + 1] ,那么一定配对,res ++ , 否则说明只有 str[i] == 0 && str[i + 1] == 1 或者 str[i] == 1 && str[i + 1] == 0 两种情况,对于这种情况直接跳过,如果str[i] 或者 str[i + 1]中的某一个是?的话,那么一定可以和下一个字符匹配,所以res++,如果是??,那么随便是 11 和 00 都可以,不必担心后面的数,假如??00 = 2 , ?? 01 = 1 ,?? 11 = 2,??10 = 1 ,说明当前的 str[i] 和 str[i + 1]无关的。所以只需分 str[i] == str[i +1] 和 str[i] 或str[i + 1] 中有一个为?即可

cpp 复制代码
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1e6 + 10;

int main()
{
    string str;
    cin >> str;
    
    int res = 0;
    for(int i = 0 ; i < str.size() - 1 ;i ++)
    {
        if(str[i] == str[i + 1])
        {
            res ++;
            i ++;
        }
        else if(str[i + 1] == '?' || str[i] == '?')
        {
            res ++;
            i ++;
        }
    }
    cout << res << endl;
    
    return 0;
}
相关推荐
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4163 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥3 天前
C++ std::set
c++