Close

Number of characters appearing in all given strings

Given a set of n strings, we have to write a program to find out the number of characters appearing in all the strings.

For example consider the following strings
{“India”, “China”, “United states”}, the letters {a,i,n} appear in all the strings.

Let us think of the following solution.

  • We first add all the characters in the first string to a set. 
  • For each string we do the following.
    • For each letter in the set, we check if it can be found the string.
    • If it is not found, we delete it from the set
  • Finally the set contains only the elements which appear in all the given strings.

Here is the C++ code which implements the above approach. For simplicity this program assumes that all the strings contains lower case alphabets only.

#include <iostream>
#include <set>
using namespace std;
int main() {
int n;
cin >> n;
int i,j;
int ch_count[26] = {0};
int result = 0;
string line;
cin >> line;
set<char> chSet;
for( i = 0; i < line.size(); i++ )
{
chSet.insert(line[i]);
}
for( i = 1; i < n; i++ )
{
cin >> line;
set<char>::iterator it;
for( it = chSet.begin(); it != chSet.end(); ++it )
{
if( line.find(*it) == string::npos )
{
chSet.erase(it);
}
}
}
cout << chSet.size() << endl;
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *