Quick and dirty imperative version:
#include <climits>
int count_common_chars(const std::string& str) {
int n = 0, common = 0, counts[CHAR_MAX - CHAR_MIN + 1] = {};
for (char c : str) {
if (c == '\n') {
common = 0;
n++;
}
if (counts[c - CHAR_MIN] == n) {
counts[c - CHAR_MIN]++;
common++;
}
}
return common;
}
Tastes may vary, but to my eyes the imperative version has some advantages:* Faster
* No allocations
* No dependencies
* Easy to add an early return if common == 0 (in the functional version it's much harder)