leetcode1702--修改后的最大二进制数

1. 题意

给定二进制串,你可以执行下面的操作任意次,求能取得的最大值。

  • 00->10
  • 10->01

leetcode1702--修改后的最大二进制数

2. 题解

找到第一个0的位置,其后面的0都可以通过变换(2)与 1 1 1交换而都位于前面。再对其进行变换(1)。

  • 我的
cpp 复制代码
class Solution {
public:
    string maximumBinaryString(string binary) {
        string ans;
        int p = 0;
        int sz = binary.size();
        while( p < sz && binary[p] == '1')
            p++;
        int b = p;

        if (p == sz)
            return binary;
        int pre_z = 0;

        while ( p < sz && binary[p] == '0')
            p++, pre_z++;

        int suf_o = 0;
        for (int i = p; i < sz; ++i) {
            if ( binary[i] == '1')
                suf_o++;
            else
                pre_z++;
        }

        ans.append(b + pre_z - 1, '1');
        ans.push_back('0');
        ans.append(suf_o, '1');
        return ans;
    }
};
  • 官解
cpp 复制代码
class Solution {
public:
    string maximumBinaryString(string binary) {
        int n = binary.size();
        int j = 0;
        for (int i = 0; i < n; i++) {
            if (binary[i] == '0') {
                while (j <= i || (j < n && binary[j] == '1')) {
                    j++;
                }
                if (j < n) {
                    binary[j] = '1';
                    binary[i] = '1';
                    binary[i + 1] = '0';
                }
            }
        }
        return binary;
    }
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/maximum-binary-string-after-change/solutions/2726979/xiu-gai-hou-de-zui-da-er-jin-zhi-zi-fu-c-put3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
Wuliwuliii2 天前
Hall定理的应用
贪心·hall定理
长安er3 天前
LeetCode121/55/45/763 贪心算法理论与经典题解析
java·数据结构·算法·leetcode·贪心算法·贪心
罗湖老棍子12 天前
瑞瑞的木板(洛谷P1334 )
c++·算法·优先队列·贪心·哈夫曼树
2401_8414956415 天前
【数据结构】最短路径的求解
数据结构·动态规划·贪心·ipython·最短路径·迪杰斯特拉算法·弗洛伊德算法
不能只会打代码15 天前
蓝桥杯--生命之树(Java)
java·算法·蓝桥杯·动态规划·贪心
闻缺陷则喜何志丹16 天前
【图论 拓扑排序 贪心 临项交换】P5603 小 C 与桌游 题解|普及+
c++·算法·图论·贪心·拓扑排序·洛谷·临项交换
小刘不想改BUG1 个月前
LeetCode 56.合并区间 Java
java·python·leetcode·贪心算法·贪心
complexor1 个月前
NOIP 2025 游记
数据结构·数学·动态规划·贪心·组合计数·树上问题·游记&总结
獭.獭.1 个月前
C++ -- 类和对象【中】
c++·析构·拷贝构造·构造·类的默认成员函数·赋值重载
hansang_IR2 个月前
【记录】四道双指针
c++·算法·贪心·双指针