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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
Aurora_th11 天前
LeetCode 2332.坐上公交的最晚时间 (双指针 + 贪心)
c++·算法·leetcode·职场和发展·贪心·双指针
Jcqsunny18 天前
[atcoder agc 004 c] AND Grid
c++·算法·构造
SkyMaths1 个月前
AGC007F 题解
贪心·性质·好题·后效性
UestcXiye1 个月前
Leetcode3256. 放三个车的价值之和最大 I
c++·leetcode·贪心·数据结构与算法
DieSnowK1 个月前
[Algorithm][贪心][跳跃游戏][加油站][单调递增的数字][坏了的计算器]详细讲解
贪心·单调递增的数字·新手向·跳跃游戏·algorithm·加油站·坏了的计算器
闻缺陷则喜何志丹1 个月前
【C++贪心】2498. 青蛙过河 II
c++·算法·leetcode·贪心·最小·最大·青蛙
逝去的秋风2 个月前
【代码随想录训练营第42期 Day26打卡 贪心Part1 - LeetCode 455.分发饼干 376. 摆动序列 53. 最大子序和
leetcode·贪心
Aurora_th2 个月前
贪心算法的初涉(双指针 + “过山车思想”)
算法·leetcode·codeforces·贪心·双指针·“过山车”思想
rgw20102 个月前
P6764 [APIO2020] 粉刷墙壁
动态规划·贪心·特殊性质·最小区间覆盖·apio
Aurora_th2 个月前
LeetCode 2844.生成特殊数字的最少操作(哈希表 + 贪心)
数据结构·c++·数学·leetcode·贪心·哈希表