
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Final String After Performing Given Operations in C++
In this tutorial, we are going to solve the following problem.
Given a string containing only characters a and b, our task is to delete the sub-string ab from the string. And print the remaining string.
Here, the idea is very simple to solve the problem. Every string with only a's and b's will shrink to either a's or b's at the end.
Let's see the steps to solve the problem.
Initialize the string.
Initialize two counter variables for a and b.
-
Iterate over the given string.
Count the a's and b's
Find the maximum from the a and b frequencies.
Print the difference between the two.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; string getTheUpdatedString(string str) { int n = str.length(); int a_count = 0, b_count = 0; for (int i = 0; i < n; i++) { if (str[i] == 'a') { a_count++; } else { b_count++; } } string updated_string = ""; if (a_count > b_count) { for (int i = 0; i < a_count - b_count; i++) { updated_string += "a"; } } else { for (int i = 0; i < b_count - a_count; i++) { updated_string += "b"; } } return updated_string; } int main() { string str = "ababababaaa"; cout << getTheUpdatedString(str) << endl; }
Output
If you run the above code, then you will get the following result.
aaa
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements