LeetCode 1702 修改后的最大二进制字符串

  • 思路
    自己的思路时间复杂度高,超时了,看了答案后恍然大悟,只需要知道第一个0的位置和0的个数就可以确定最后的最大数
  • 代码
    看答案后的代码,这里可以用一些库函数进行优化
cpp 复制代码
class Solution {
public:
    string maximumBinaryString(string binary) {
        int len = binary.length();
        string ans(len, '1');
        int first_zero = 0, num_zero = 0;
        for (int i = 0; i < len; i++) {
            if (binary[i] == '0') {
                num_zero++;
            }
        }

        for (int i = 0; i < len; i++) {
            if (binary[i] == '0') {
                first_zero = i;
                break;
            }
        }

        if (num_zero != 0) {
            ans[first_zero + num_zero - 1] = '0';
        }
        return ans;
    }
};

自己代码

cpp 复制代码
class Solution {
public:
    string maximumBinaryString(string binary) {
        stack<char> stk1;
        string ans;
        
        for(int i = 0; i < binary.length(); i++) {
            if (i == 0) {
                stk1.push(binary[i]);
                continue;
            }

            if (binary[i] == '0') {
                if (stk1.top() == '1') {
                    int num = 0;
                    while(!stk1.empty() && stk1.top() == '1') {
                        num++;
                        stk1.pop();
                    } 
                    if (stk1.empty()) {
                        while(num--) stk1.push('1');
                        stk1.push('0');
                    } else {
                        stk1.pop();
                        stk1.push('1');
                        stk1.push('0');
                        while(num--) stk1.push('1');
                    }
                } else {
                    stk1.pop();
                    stk1.push('1');
                    stk1.push('0');
                }
            } else {
                stk1.push('1');
            }
        }

        while(!stk1.empty()){
            ans.push_back(stk1.top());
            stk1.pop();
        }

        reverse(ans.begin(), ans.end());
        return ans;
    }
};
相关推荐
JiaJZhong33 分钟前
力扣.最长回文子串(c++)
java·c++·leetcode
凌肖战2 小时前
力扣网编程150题:加油站(贪心解法)
算法·leetcode·职场和发展
吃着火锅x唱着歌2 小时前
LeetCode 3306.元音辅音字符串计数2
算法·leetcode·c#
kngines2 小时前
【力扣(LeetCode)】数据挖掘面试题0003: 356. 直线镜像
leetcode·数据挖掘·直线镜像·对称轴
不見星空2 小时前
【leetcode】1751. 最多可以参加的会议数目 II
算法·leetcode
不見星空2 小时前
leetcode 每日一题 3439. 重新安排会议得到最多空余时间 I
算法·leetcode
SsummerC2 小时前
【leetcode100】下一个排列
python·算法·leetcode
shylyly_4 小时前
专题一_双指针_查找总价格为目标值的两个商品
c++·算法·leetcode·双指针·查找总价格为目标值的两个商品·和为s的两个数
嗜好ya6 小时前
LeetCode 560: 和为K的子数组
数据结构·算法·leetcode
myloveasuka7 小时前
leetcode11.盛最多水的容器
c语言·数据结构·c++·leetcode