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;
    }
};
相关推荐
破东风1 小时前
leetcode每日一题:替换子串得到平衡字符串
算法·leetcode·滑动窗口
梭七y7 小时前
【力扣hot100题】(032)排序链表
算法·leetcode·链表
SsummerC7 小时前
【leetcode100】数组中的第K个最大元素
python·算法·leetcode
编程绿豆侠7 小时前
力扣HOT100之链表:206. 反转链表
算法·leetcode·链表
记得早睡~9 小时前
leetcode51-N皇后
javascript·算法·leetcode·typescript
luckyme_13 小时前
leetcode-代码随想录-哈希表-有效的字母异位词
算法·leetcode·散列表
luckyme_13 小时前
leetcode 代码随想录 数组-区间和
c++·算法·leetcode
jyyyx的算法博客14 小时前
Leetcode 857 -- 贪心 | 数学
算法·leetcode·贪心·嗜血
luckyme_15 小时前
leetcode-代码随想录-哈希表-哈希理论基础
leetcode·哈希算法·散列表
梭七y17 小时前
【力扣hot100题】(048)二叉树的最近公共祖先
算法·leetcode·职场和发展