- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to count number of characters to be removed to get good string
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
Advertisements