Remove characters from a String that appears exactly K times
To Remove characters from a String that appears exactly K times, we will create a hash table of all the alphabet elements i.e. a - z, and initialize all values to 0. Then we'll iterate over given string. We'll increment, value of character by 1 every time we encounter it. Finally, we'll iterate over array again and delete all the characters whose values in our hash table is eual to k.
A formal problem would like this.
Given a string of character of length N remove the character that appears exactly K times in the string. String, N and K will be given as input.
Example input
N = 13
String = hackersfriend
K = 2
Example Output
hacksfind
Here r and e were appearing 2 times so they are removed.
Solution
Let's implement our approach which we discussed in the begining.
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26; // since chars are a - z
string CleanCharK(string s, int k)
{
// make Hash table and initialise to 0
int hash[MAX_CHAR] = { 0 };
// store the occurance of chars in hash table
int n = s.length();
for (int i = 0; i < n; ++i)
hash[s[i] - 'a']++;
string cleanString = ""; // we'll keep asnwer string here.
for (int i = 0; i < n; ++i) {
// keep only those which dont appear k times
if (hash[s[i] - 'a'] != k) {
cleanString += s[i];
}
}
return cleanString;
}
int main()
{
string s = "hackersfriend";
int k = 2;
cout << CleanCharK(s, k);
return 0;
}