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


    生成交替二进制字符串的最小操作数【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;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 复杂度分析

        • 时间复杂度: 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;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 复杂度分析

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

        但是还没第一种快

        image-20221129093140505

  • 相关阅读:
    重新定义分析 - EventBridge 实时事件分析平台发布
    position sticky与overflow冲突失效无作用,解决办法
    【python】直方图正则化详解和示例
    算法竞赛进阶指南 搜索 0x24 迭代加深
    波动率和波动率曲面套利
    steamvr2.0 + curvedUI 实现与UI射线交互
    关于数据权限的设计
    WPF由文本框输入的内容动态渲染下拉框
    Go简单入门
    此处不允许使用特性 setup 报错
  • 原文地址:https://blog.csdn.net/Tikitian/article/details/128091759