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

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

生成交替二进制字符串的最小操作数【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 ) ,两次遍历字符串s
  • 空间复杂度:O ( 1 )


473cf6121372d9fc3aceedc7837c4c7b.png


  • 优化:变成这两种不同的交替二进制字符串所需要的最少操作数加起来等于 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 ),一次遍历字符串s,
  • 空间复杂度:O ( 1 )


但是还没第一种快


652ad30606062fe81b8d8f39e141bdb8.png

目录
相关文章
|
7月前
【Leetcode -680.验证回文串Ⅱ -693.交替位二进制数】
【Leetcode -680.验证回文串Ⅱ -693.交替位二进制数】
23 0
|
7月前
【Leetcode -696.计数二进制字串 -697.数组的度】
【Leetcode -696.计数二进制字串 -697.数组的度】
18 0
|
3月前
LeetCode题 338比特位计数,20有效的括号,415字符串相加
LeetCode题 338比特位计数,20有效的括号,415字符串相加
37 0
|
4月前
|
存储
leetcode:415. 字符串相加(模拟竖式计算)
leetcode:415. 字符串相加(模拟竖式计算)
25 0
|
5月前
|
存储 算法
【LeetCode】每日一题&最后一个单词的长度&投票法求解多数元素&异或操作符巧解只出现一次的数字&整数反转
【LeetCode】每日一题&最后一个单词的长度&投票法求解多数元素&异或操作符巧解只出现一次的数字&整数反转
|
7月前
|
算法
【每日挠头算法(4)】字符串相加|字符串相乘
【每日挠头算法(4)】字符串相加|字符串相乘
|
7月前
|
算法 测试技术 C++
剑指offer(C++)-JZ20:表示数值的字符串(算法-模拟)
剑指offer(C++)-JZ20:表示数值的字符串(算法-模拟)
|
11月前
|
存储 机器学习/深度学习
母牛的故事 替换空格 二进制中1的个数 不使用第三个变量交换a,b的值
母牛的故事 替换空格 二进制中1的个数 不使用第三个变量交换a,b的值
68 0