蓝桥杯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;
}
相关推荐
xlp666hub18 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网19 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub21 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星1 天前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub2 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
不想写代码的星星2 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星3 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus5 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit7 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_8 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++