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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
qz5zwangzihan13 天前
题解:Atcoder Beginner Contest abc467 F - Email Scheduling Optimization
c++·贪心·atcoder·平衡树·abc467·abc467_f·fhq-treap
cpp_25018 天前
P6625 [省选联考 2020 B 卷] 卡牌游戏
数据结构·c++·算法·前缀和·贪心·洛谷题解·省选
cpp_250110 天前
P10098 [ROIR 2023] 地铁建设 (Day 2)
数据结构·c++·算法·贪心·二分答案·洛谷题解
tkevinjd11 天前
力扣300-最长递增子序列
算法·leetcode·职场和发展·动态规划·贪心
芜湖xin12 天前
【题解-信息学奥赛一本通】1226:装箱问题
贪心
Tisfy1 个月前
LeetCode 3689.最大子数组总值 I:What The Medium
算法·leetcode·题解·贪心·模拟·脑筋急转弯
Misnearch2 个月前
3635. 最早完成陆地和水上游乐设施的时间II
leetcode·贪心·排序
EllinY2 个月前
CF2217E Definitely Larger 题解
c++·笔记·算法·构造
不太会a2 个月前
Educational Codeforces Round 175 (Rated for Div. 2) C
贪心·二分
芜湖xin2 个月前
【题解-洛谷】P1012 [NOIP 1998 提高组] 拼数
算法·贪心