最小化翻转次数,使得字符串中不存在连续的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 

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对的详细内容,更多请关注【创想鸟】其它相关文章!

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

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2582977.html

(0)
上一篇 2025年3月6日 14:27:16
下一篇 2025年2月27日 23:53:01

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论