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.
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; }
If you run the above code, then you will get the following result.
aaa
If you have any queries in the tutorial, mention them in the comment section.