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;
    }
};
相关推荐
夏鹏今天学习了吗14 小时前
【LeetCode热题100(56/100)】组合总和
算法·leetcode·职场和发展
微笑尅乐15 小时前
三种方法解开——力扣3370.仅含置位位的最小整数
python·算法·leetcode
夏鹏今天学习了吗1 天前
【LeetCode热题100(57/100)】括号生成
算法·leetcode·职场和发展
三花聚顶<>1 天前
310.力扣LeetCode_ 最小高度树_直径法_DFS
算法·leetcode·深度优先
努力学算法的蒟蒻1 天前
day04(11.2)——leetcode面试经典150
算法·leetcode
Tisfy1 天前
LeetCode 3217.从链表中移除在数组中存在的节点:哈希表(一次遍历)
leetcode·链表·散列表
小白菜又菜1 天前
Leetcode 495. Teemo Attacking
算法·leetcode·职场和发展
.柒宇.1 天前
力扣hot100----15.三数之和(java版)
java·数据结构·算法·leetcode
程序员阿鹏1 天前
56.合并区间
java·数据结构·算法·leetcode
Brookty2 天前
【算法】位运算| & ^ ~ -n n-1
学习·算法·leetcode·位运算