Problem Statement:
Given a string, get all the duplicates and print their count.
Example
String: helloo
l = 2
o = 2
Solution
Solution is very simple. Take an array whose size is 256.
Then initialize it to 0.
Then convert the character into its ascii value and increment the count at that index.
Print the characters whose count is greater than 1
Solution in C++
#include <vector>
#include <algorithm>
//visit www.ProDeveloperTutorial.com for 450+ solved questions
#include <iostream>
#include <string>
using namespace std;
#define NO_OF_CHARS 256
void print_duplicate(string s)
{
int count[NO_OF_CHARS] = {};
for(int i=0; i<s.size(); i++)
count[s[i]]++; //increment the count of each character by using ASCII
for(int i=0; i<s.size(); i++)
{
if(count[s[i]] > 1)
{
cout<<s[i]<<" count = "<<count[s[i]]<<endl;
count[s[i]] = 0;
}
}
}
int main()
{
string s = "hellooo";
cout<<"Input string is "<<s<<endl;
print_duplicate(s);
}
Output:
Input string is hellooo
l count = 2
o count = 3