fork download
  1. // CPP Program to find all the common characters
  2. // in n strings
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. const int MAX_CHAR = 26;
  7.  
  8. void commonCharacters(string str[], int n)
  9. {
  10. // primary array for common characters
  11. // we assume all characters are seen before.
  12. bool prim[MAX_CHAR];
  13. memset(prim, true, sizeof(prim));
  14.  
  15. // for each string
  16. for (int i = 0; i < n; i++) {
  17.  
  18. // secondary array for common characters
  19. // Initially marked false
  20. bool sec[MAX_CHAR] = { false };
  21.  
  22. // for every character of ith string
  23. for (int j = 0; str[i][j]; j++) {
  24.  
  25. // if character is present in all
  26. // strings before, mark it.
  27. if (prim[str[i][j] - 'a'])
  28. sec[str[i][j] - 'a'] = true;
  29. }
  30.  
  31. // copy whole secondary array into primary
  32. memcpy(prim, sec, MAX_CHAR);
  33. }
  34.  
  35. // displaying common characters
  36. for (int i = 0; i < 26; i++)
  37. if (prim[i])
  38. printf("%c ", i + 'a');
  39. }
  40.  
  41. // Driver's Code
  42. int main()
  43. {
  44. string str[] = { "1123",
  45. "453",
  46. "567",
  47. "8" };
  48. int n = sizeof(str)/sizeof(str[0]);
  49. commonCharacters(str, n);
  50. return 0;
  51. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty