Deletions of “01” or “10” in binary string to make it free from “01” or “10" in C++?


Let us first declare our initial string and calculate its length and pass them to the deleteSubstr(str,length) function.

string str = "01010110011";
int length = str.length();
cout <<"Count of substring deletion"<< deleteSubstr(str, length);

Inside of the deleteSubstr(string str, int length) function the for loop runs till I is less than length and increments the count_0 and count_1 variable on encounter of 0 and 1 respectively. The function then returns the min value of the count_0 and count_1.

int deleteSubstr(string str, int length){
   int count_0 = 0, count_1 = 0;
   for (int i = 0; i < length; i++) {
      if (str[i] == '0')
         count_0++;
      else
         count_1++;
   }
   return min(count_0, count_1);
}

Example

Let us see the following implementation of deletions of “01” or “10” in binary string to make it free from “01” or “10”−

 Live Demo

#include <iostream>
using namespace std;
int deleteSubstr(string str, int length){
   int count_0 = 0, count_1 = 0;
   for (int i = 0; i < length; i++) {
      if (str[i] == '0')
         count_0++;
      else
         count_1++;
   }
   return min(count_0, count_1);
}
int main(){
   string str = "01010110011";
   int length = str.length();
   cout <<"Count of substring deletion "<< deleteSubstr(str, length);
   return 0;
}

Output

The above code will produce the following output −

Count of substring deletion 5

Updated on: 16-Jan-2021

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements