3 ms·
Quick and dirty imperative version: #include <climits> int count_common_chars(const std::string& str) { int n = 0, common = 0, counts[CHAR_MAX -
by cousin_it 10y ago
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)
- tzs 10y ago> counts[CHAR_MAX - CHAR_MIN] Shouldn't that be counts[CHAR_MAX - CHAR_MIN + 1] ?
- cousin_it 10y agoGood catch, thanks!
- deleted 10y ago[deleted]
- anthay 10y agoThat's cool and I agree about the advantages you mention. In your code \n must be a line separator rather than a line terminator. (Otherwise, if the last line is \n terminated, the function returns 0.)
- cousin_it 10y agoYeah, fair point.