总结
豆包 AI 助手文章总结
首页 > 后端开发 > C++ > 正文

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

王林
发布: 2023-09-08 11:29:02
转载
1202人浏览过

最小化翻转次数,使得字符串中不存在连续的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 <bits/stdc++.h>
using namespace std;
// Function to get the total number of minimum flips required so the string does not contain any consecutive 0’s
int 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对的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号