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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
Alfred king14 小时前
面试150 IPO
面试·职场和发展·贪心·数组··排序
christ_lrs1 天前
2025.7.25 测试 总结
贪心·模拟
christ_lrs4 天前
2025.7.22 测试 总结
贪心·dp
阳洞洞2 个月前
376. Wiggle Subsequence
leetcode·贪心
Tisfy2 个月前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·
阳洞洞2 个月前
leetcode 455. Assign Cookies和2410. Maximum Matching of Players With Trainers
leetcode·贪心
咚咚轩2 个月前
蓝桥杯11届国B 答疑
蓝桥杯·贪心
咚咚轩2 个月前
蓝桥杯13届 卡牌
蓝桥杯·贪心
haaaaaaarry3 个月前
【贪心】C++ 活动安排问题
开发语言·c++·算法·贪心
想成为配环境大佬3 个月前
P8739 [蓝桥杯 2020 国 C] 重复字符串
算法·蓝桥杯·贪心