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;
    }
};
相关推荐
Tisfy5 小时前
LeetCode 2187.完成旅途的最少时间:二分查找
算法·leetcode·二分查找·题解·二分
Mephisto.java5 小时前
【力扣 | SQL题 | 每日四题】力扣2082, 2084, 2072, 2112, 180
sql·算法·leetcode
丶Darling.5 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
一个不知名程序员www7 小时前
leetcode第189题:轮转数组(C语言版)
c语言·leetcode
一叶祇秋8 小时前
Leetcode - 周赛417
算法·leetcode·职场和发展
夜雨翦春韭10 小时前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
一直学习永不止步10 小时前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序
戊子仲秋11 小时前
【LeetCode】每日一题 2024_10_2 准时到达的列车最小时速(二分答案)
算法·leetcode·职场和发展
￴ㅤ￴￴ㅤ9527超级帅12 小时前
LeetCode hot100---二叉树专题(C++语言)
c++·算法·leetcode
liuyang-neu12 小时前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先