C++ Program to count number of characters to be removed to get good string

C++Server Side ProgrammingProgramming

Suppose we have a string S. S contains two types of characters in S, the 'x' and 'a'. We have to count what will be the longest string remaining after removal of few characters in S so that it becomes good string. A string is good if it has strictly more than the half of its length filled with character 'a'.

So, if the input is like S = "xaxxxxa", then the output will be 3, because if we remove 4 'x's, the string will be "xaa" and this is a good string whose length is 3.

Steps

To solve this, we will follow these steps −

x := 2 * count the number of 'a' in S
n := size of S
return minimum of n and x

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(string S) {
   int x = 2 * count(S.begin(), S.end(), 'a') - 1;
   int n = S.size();
   return min(n, x);
}
int main() {
   string S = "xaxxxxa";
   cout << solve(S) << endl;
}

Input

"xaxxxxa"

Output

3
raja
Updated on 04-Mar-2022 06:23:53

Advertisements