最小化翻转次数,使得字符串中不存在连续的0对

最小化翻转次数,使得字符串中不存在连续的0对

Here, we require to manipulate the binary string so that it doesn’t contain any consecutive zeros. If we find consecutive zeros, we need to change any zero to 1. So, we require to count the total number of 0 to 1 conversion we should make to remove all consecutive zeros from the string.

问题陈述 − 我们给定一个只包含0和1的二进制字符串‘str’。我们需要找到所需的最小翻转次数,以便结果字符串不包含连续的零。

示例示例

Input –  0101001
Output – 1

Explanation

我们需要翻转只有倒数第二个零。

Input –  str = 00100000100
Output – 4

Explanation

我们需要翻转第2、第5、第7和第11个零,以消除所有连续的零对。

Input –  0101010101
Output – 0

Explanation

我们不需要进行任何翻转,因为字符串中没有连续的零。

方法一

在这种方法中,我们将从头到尾迭代遍历字符串,并在其中包含任何连续的零时翻转字符。最后,我们可以得到从给定的二进制字符串中删除所有连续零所需的最小翻转次数。

算法

Step 1 − Initialize the ‘cnt’ variable with zero, storing a total number of flips.

Step 2 − Iterate through the binary string using the loop.

Step 3 − If the character at index ‘I’ and index ‘I +1’ is 0, flip the next character, and increase the value of the ‘cnt’ variable by 1.

步骤 4 – 当 for 循环的迭代完成时,返回 ‘cnt’ 的值。

Example

#include using namespace std;// Function to get the total number of minimum flips required so the string does not contain any consecutive 0’sint findCount(string str, int len){   // initialize the count   int cnt = 0;      // iterate over the string   for (int i = 0; i < len - 1; i++){         // If two consecutive characters are the same      if (str[i] == '0' && str[i + 1] == '0'){               // Flip the next character         str[i + 1] = '1';                  // increment count         cnt++;                 }   }   return cnt;}int main(){   string str = "00100000100";   int len = str.length();   cout << "The minimum numbers of flips required so that string doesn't contain any pair of consecutive zeros - " << findCount(str, len);   return 0;}

Output

The minimum numbers of flips required so that string doesn't contain any pair of consecutive zeros - 4

Time complexity − O(N), as we iterate through the binary string.

Space complexity − O(1), as we use constant space to store total counts.

结论

我们学会了计算从给定的二进制字符串中移除连续的零对所需的最小翻转次数。用户可以尝试计算从给定的二进制字符串中移除连续的一对所需的最小翻转次数。

以上就是最小化翻转次数,使得字符串中不存在连续的0对的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444678.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 21:47:23
下一篇 2025年12月17日 21:47:31

相关推荐

  • 电脑窗口最小化快捷键 快速最小化组合键

    windows系统下最小化当前窗口的快捷键是win + m,该组合键会将所有打开的窗口全部最小化并显示桌面;若只想最小化当前窗口,则可使用win + down arrow(向下箭头),按一次恢复非最大化状态,再按一次则最小化;alt + space + n也可实现最小化当前窗口,但操作步骤更多;ma…

    2025年11月7日 电脑教程
    000
  • Linux最小化安装方法教程

    1,linux安装网络自动配置: 2,linux硬盘分配 1,/boot 用来存放与 Linux 系统启动有关的程序,比如启动引导装载程序等,建议大小为 100-200MB 。 2,swap 实现虚拟内存,建议大小是物理内存的 1~2 倍。 3,/ 使用全部的磁盘空间 4,linux最小化安装   …

    2025年11月1日 运维
    000

发表回复

登录后才能评论
关注微信