【每日一题Day41】生成交替二进制字符串的最小操作数 | 模拟 位运算

本文探讨了如何通过最少的操作次数将给定的二进制字符串转化为交替形式,分享了一种优化算法,从两种基本交替模式出发,减少遍历次数,最终降低了时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生成交替二进制字符串的最小操作数【LC1758】

You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.

The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.

Return the minimum number of operations needed to make s alternating.

隔离第五天 终于喝到酸奶啦>o<

  • 思路:长度一定的交替二进制字符串有两种可能性,以字符0开头的0101字符串和以字符1开头的1010字符串,因此只需要将字符串s与这两种字符串进行比较,记录不相同的字符个数,最后返回较小值即可

  • 实现:使用异或操作记录该位应是1还是0:flag ^= 1;

    class Solution {
        public int minOperations(String s) {    
            return Math.min(countOperations(s,0),countOperations(s,1));    
        }
        public int countOperations(String s, int flag){
            int n = s.length();
            int count = 0;
            for (int i = 0; i < n; i++){
                if (s.charAt(i) == '0' + flag){
                    count++;
                }
                flag ^= 1;
            }
            return count;
        }
    }
    
    • 复杂度分析

      • 时间复杂度:O(n)O(n)O(n),两次遍历字符串s
      • 空间复杂度:O(1)O(1)O(1)

      image-20221129093115019

  • 优化:变成这两种不同的交替二进制字符串所需要的最少操作数加起来等于 s的长度,我们只需要计算出变为其中一种字符串的最少操作数,就可以推出另一个最少操作数,然后取最小值即可。

    class Solution {
        public int minOperations(String s) {
            int n = s.length();
            int n0 = countOperations(s,0);     
            return Math.min(n-n0, n0);    
        }
        public int countOperations(String s, int flag){
            int n = s.length();
            int count = 0;
            for (int i = 0; i < n; i++){
                if (s.charAt(i) == '0' + flag){
                    count++;
                }
                flag ^= 1;
            }
            return count;
        }
    }
    
    • 复杂度分析

      • 时间复杂度:O(n)O(n)O(n),一次遍历字符串s,
      • 空间复杂度:O(1)O(1)O(1)

      但是还没第一种快

      image-20221129093140505

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值