Count of operations to make a binary string “ab” free in C++

C++Server Side ProgrammingProgramming

We are given a string which can contain “ab” and the task is to calculate the count of operations required to remove or delete “ab” from the string. So, our task is to firstly check whether the string contains “ab” or not if yes then we have to make string “ab” free.

Input − string str = "ababaa"

Output − Count of operations to make a binary string “ab” free are − 4

Explanation − As we can see in the string “ab” pattern is occurring two times so we will replace “ab” with “bba” so the count of operations is 1 and now the string is bbaabaa. Again, we will replace “ab” with “bba” so the count of operations is 2 and now the string is bbabbaaa. We are having one more “ab” so the count of operations is 3 and now the string is bbabbaaa. As we continue replacing the examined “ab” with “bba” the string will become “ab” free.

Input − str = "abaa"

Output − Count of operations to make a binary string “ab” free are − 1

Explanation − As we can see in the string “ab” pattern is occurring one time so we will replace “ab” with “bba” so the count of operations is 1 and now the string is bbaaa. Now, the string is “ab” free and the count is 1.

Approach used in the below program is as follows

  • Input a string and calculate the length of a string and pass the data to the function for further processing.

  • Declare a temporary variable count to store the operations required to make string “ab” free.

  • Create a character array of size string length + 1

  • Store the character of the string in an array using strcpy() method.

  • Start Loop FOR from 0 till the length of a string

  • Inside the loop, check IF arr[length - i - 1] = ‘a’ then set count as count + 0 and set total variable as total * 2

  • Else, increment the count for total by 1.

  • Return the count

  • Print the result.

Example

#include<bits/stdc++.h>
using namespace std;
int operations_ab_free(string str, int len){
   int count = 0;
   char arr[length + 1];
   strcpy(arr, str.c_str());
   int total = 0;
   for (int i = 0; i < len; i++){
      if (arr[len - i - 1] == 'a'){
         count = (count + total);
         total = (total * 2);
      }
      else{
         total++;
      }
   }
   return count;
}
int main(){
   string str = "ababaa";
   int length = str.length();
   cout<<"Count of operations to make a binary string “ab” free are: "<<operations_ab_free(str,
length)<<endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of operations to make a binary string “ab” free are: 4
raja
Published on 02-Dec-2020 12:33:48
Advertisements