Prefixes with more a than b in C++


In this problem, we are given string str containing only a and b and an integer N such that a string is created by appending str n times. Our task is to print the total number of substring in which the count of a’s is more than the count of b.

Let’s take an example to understand the problem

Input: aab 2
Output: 9
Explanation: created string is aabaab.
Substrings with count(a) > count(b) : ‘a’ , ‘aa’, ‘aab’, ‘aaba’, ‘aabaa’, ‘aabaab’, ‘aba’, ‘baa’, ‘abaa’.

To solve this problem, we will have to check if the string contains the required prefix subsets. Here, we will check for the string str not the full version. Here, w will be checking the string based on the prefix and the count of occurrence of a and b.

This program will show the implementation of our solution

Example

 Live Demo

#include <iostream>
#include <string.h>
using namespace std;
int prefixCount(string str, int n){
   int a = 0, b = 0, count = 0;
   int i = 0;
   int len = str.size();
   for (i = 0; i < len; i++) {
      if (str[i] == 'a')
         a++;
      if (str[i] == 'b')
         b++;
      if (a > b) {
      count++;
   }
}
if (count == 0 || n == 1) {
   cout<<count;
   return 0;
}
if (count == len || a - b == 0) {
   cout<<(count*n);
   return 0;
}
int n2 = n - 1, count2 = 0;
while (n2 != 0) {
   for (i = 0; i < len; i++) {
      if (str[i] == 'a')
         a++;
      if (str[i] == 'b')
         b++;
      if (a > b)
      count2++;
   }
   count += count2;
   n2--;
   if (count2 == 0)
      break;
   if (count2 == len) {
      count += (n2 * count2);
      break;
   }
   count2 = 0;
   }
   return count;
}
int main() {
   string str = "aba";
   int N = 2;
   cout<<"The string created by using '"<<str<<"' "<<N<<" times has ";
   cout<<prefixCount(str, N)<<" substring with count of a greater than count of b";
   return 0;
}

Output

The string created by using 'aba' 2 times has 5 substring with count of a greater than count of b

Updated on: 03-Feb-2020

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements