Updated alternative version
As mentioned above, using std::array<int, 256>
is one way to improve the speed of the code considerably. This also incorporates AJNeufeld's suggestion in a comment about using an overall counter to further simplify. It also processes the shortest string first, which should help. With the strings I have been using to test, this code is around 10x faster than the original two versions.
bool isAnagram4(const std::string& a, const std::string& b)
{
auto s1{a.size() < b.size() ? a : b};
auto s2{a.size() < b.size() ? b : a};
int count{0};
std::array<int, 256> charCounter{};
for (auto c : s1) {
if (isalpha(c)) {
++charCounter[std::tolower(c)];
++count;
}
}
if (count > s2.length()) {
return false;
}
for (auto c : s2) {
if (isalpha(c)) {
if (--charCounter[std::tolower(c)] < 0)
return false;
--count;
}
}
return count == 0;
}