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;
    }
};
相关推荐
渐暖°6 分钟前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困7 分钟前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van20 分钟前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
alphaTao27 分钟前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode
We་ct1 小时前
LeetCode 54. 螺旋矩阵:两种解法吃透顺时针遍历逻辑
前端·算法·leetcode·矩阵·typescript
We་ct3 小时前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
tod1133 小时前
力扣高频 SQL 50 题阶段总结(四)
开发语言·数据库·sql·算法·leetcode
iAkuya4 小时前
(leetcode)力扣100 57电话号码的字母组合(回溯)
算法·leetcode·深度优先
想进个大厂7 小时前
代码随想录day31 贪心05
数据结构·算法·leetcode
橘颂TA7 小时前
【剑斩OFFER】算法的暴力美学——力扣 207 题:课程表
数据结构·c++·算法·leetcode·职场和发展