// CPP Program to find all the common characters
// in n strings
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
void commonCharacters(string str[], int n)
{
// primary array for common characters
// we assume all characters are seen before.
bool prim[MAX_CHAR] = {true};
//memset(prim, true, sizeof(prim));
// for each string
for (int i = 0; i < n; i++) {
// secondary array for common characters
// Initially marked false
bool sec[MAX_CHAR] = { false };
// for every character of ith string
for (int j = 0; str[i][j]; j++) {
// if character is present in all
// strings before, mark it.
if (prim[str[i][j] - 'a'])
sec[str[i][j] - 'a'] = true;
}
// copy whole secondary array into primary
//memcpy(prim, sec, MAX_CHAR);
for(int k=0;k<n;k++)
prim[k] = sec[k];
}
// displaying common characters
for (int i = 0; i < 26; i++)
if (prim[i])
printf("%c ", i + 'a');
}
// Driver's Code
int main()
{
string str[] = { "geeksforgeeks",
"gemkstones",
"acknowledges",
"aguelikes" };
int n = sizeof(str)/sizeof(str[0]);
commonCharacters(str, n);
return 0;
}
We use two hash arrays of size 26 (for a-z, where 0 is a, and z is 25).
The approach is simple, if we have seen a character before we’ll mark it and if we haven’t then ignore the character because it is not a common one.
why does this code not give desired output? Whereas if I use memset(prim,true,sizeof(prim))
instead of bool prim[MAX_CHAR] = {true};
for initialization and memcpy(prim,sec,MAX_CHAR)
instead of for(int k=0;k<n;k++) prim[k] = sec[k];
for copying the boolean array sec[] in prim[] it works just fine.